3

I am new to java coding. I have an application thats can send mails, implemented in Java. I want to put a HTML link inside the mail, but when I put a html link, it shows an error saying ; is missing even though everything is correct.

String msgbody = "This is a reminder mail"; 
String link = "<a href="http://abcd.efg.com" target="_blank">http://abcd.efg.com</a>"; 
msgbody = msgbody + link;

Is there anything wrong if I use a string like this?

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245

3 Answers3

5

You need to escape quotes in string literals.

Instead of

String link = "<a href="http://abcd.efg.com" target="_blank">http://abcd.efg.com</a>";

try

String link = "<a href=\"http://abcd.efg.com\" target=\"_blank\">http://abcd.efg.com</a>";

For more info see "Characters"

Escape Sequences

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:

...

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");
Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
3

you can use escape method as answered above or you can make use of single quotes.as below :

String link = "<a href='http://abcd.efg.com' target='_blank'>http://abcd.efg.com</a>"; 

Single quotes just works fine with HTML.

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
1

use multiLine Strings is included in JDK 15:

String msgbody = "This is a reminder mail";
String link = """
<a href="http://abcd.efg.com" target="_blank">http://abcd.efg.com</a>""";
msgbody = msgbody + link;
SL5net
  • 2,282
  • 4
  • 28
  • 44