Search code examples
javahtmlencodingmailto

Convert String in html format to mailto link


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

By example, I have this String "S&D" will be display in a html correctly "S&D". But now I need to have a mailto link in my web page.

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

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

There is a library to do that?

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


Solution

  • Quoting RFC 6068(thanks JB Nizet):

    When producing 'mailto' URIs, all spaces SHOULD be encoded as %20, and '+' characters MAY be encoded as %2B. Please note that '+' characters are frequently used as part of an email address to indicate a subaddress, as for example in <[email protected]>.

    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 = "[email protected]".replace("+", "%2B");
    String link = String.format("mailto:%s?subject=%s&body=%s", email, subject, body);
    System.out.println(StringEscapeUtils.escapeHtml(link));
    

    Output:

    mailto:[email protected]?subject=my%20subject&amp;body=S%26D
    

    Which may be used in a link like so:

    <a href="mailto:[email protected]?subject=my%20subject&amp;body=S%26D">mail me</a>
    

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