The provision, known as Section 66A of the 2008 Information Technology Act, says sending such messages is a crime punishable by up to three years in prison.
In its ruling, the Supreme Court said the provision was "clearly vague" in not clarifying what should be construed as offensive. It also said the provision violates people's freedom of speech and their right to share information.
"The public's right to know is directly affected," the judges said in their ruling, deeming the provision unconstitutional.
A law student who filed the legal challenge in 2012, Shreya Singhal, applauded the court's rejection of a provision she said was "grossly offensive to our rights, our freedom of speech and expression."
"Today the Supreme Court has upheld that, they have supported our rights," Singhal said. "I am ecstatic."
The law has been invoked at least 10 times in recent years, most often in cases involving criticism of political leaders.
In 2012, a chemistry professor in Kolkata was arrested for forwarding a cartoon making fun of West Bengal's top elected official, Mamata Banerjee.
Police arrested a man last year for saying on Facebook that Prime Minister Narendra Modi, then still a candidate, would start a holocaust in India if elected to office.
And last week, police in the northern state of Uttar Pradesh arrested a teenage student for posting comments on Facebook he attributed to a top state minister.
Former finance and home minister P. Chidambaram welcomed the Supreme Court ruling, although his son had filed a police complaint in 2012 against a businessman for allegedly disparaging him in Twitter messages.
"The section was poorly drafted and was vulnerable," Chidambaram said of the law, which was passed while his Congress party was in power. "It was capable of being misused and, in fact, it was misused."
High court OKs Trump’s travel ban, rejects Muslim bias claim