Convert html string to mailto link

In Java webapp, I need an automatic converter to convert String for use in a mailto link

For example, I have this line "S & D" will be displayed in html correctly "S & D". But now I need to have a mailto link on my web page.

<a href="mailto:?subject=my%20subject&body=S&amp;D">share</a> 

its invalid character is "&", so I need to convert "&" to "% 26".

Is there a library for this?

I tried java.net.URLEncoder, but it only changed "&". not "&" and it replaces the space with "plus" + "I tried java.net.URI, but she did nothing for the character" & "!

+4
source share
1 answer

Quote RFC 6068 (thanks to JB Nizet):

When creating the mailto URI, all spaces MUST be encoded as% 20 and the characters + can be encoded as% 2B. Please note: "+" characters are often used as part of an email address to specify a subaddress, for example, in < bill+ietf@example.org > .

Updated code:

 String subject = URLEncoder.encode("my subject", "utf-8").replace("+", "%20"); String body = URLEncoder.encode("S&D", "utf-8").replace("+", "%20"); // Email addresses may contain + chars String email = " test@example.com ".replace("+", "%2B"); String link = String.format("mailto:%s?subject=%s&body=%s", email, subject, body); System.out.println(StringEscapeUtils.escapeHtml(link)); 

Output:

 mailto: test@example.com ?subject=my%20subject&amp;body=S%26D 

What can be used in such a link:

 <a href="mailto: test@example.com ?subject=my%20subject&amp;body=S%26D">mail me</a> 

StringEscapeUtils.escapeHtml (String str) from Apache Commons Lang .

+9
source

All Articles