Search code examples
javaemailutf-8urlencodemailto

Java: Encoding of a mailto link with subject and plain text multiline body


I´ve googled a lot, but I wasn´t able to find a solution to my problem. I need to encode a mailto: link with subject and body to UTF-8 in java.

The body consists of plain text

Is there any method which encodes:

  • the whole string in UTF-8, for example Ä to %C3%84S
  • blanks into %20 instead of +
  • \r\n into %0D%0A
  • / to %2f

Thank you for your help!


Solution

  • You want the URLEncode.encode(String s, String enc) method. The second parameter should be the string UTF-8.

    It does encode spaces as + instead of %20, which is valid for query parameters; you can always just special-case that and replace all of the former with the latter. Example:

    import java.net.URLEncoder;
    import java.util.regex.Pattern;
    
    public class Foobar {
      private static Pattern space = Pattern.compile("\\+");
      public static void main(String[] args) throws Exception {
        String first = URLEncoder.encode("Ä+ \r\n/", "UTF-8");
        String second = space.matcher(first).replaceAll("%20");
        System.out.println(second);
      }
    }
    

    This outputs:

    %C3%84%2B%20%0D%0A%2F