I am trying to open new email from my Java app:

        String str=String.valueOf(email);
        String body="This is body";
        String subject="Hello worlds";
        String newStr="mailto:"+str.trim()+"?subject="+URLEncoder.encode(subject,"UTF-8")+"&body="+URLEncoder.encode(body, "UTF-8")+"";
        Desktop.getDesktop().mail(new URI(newStr));

Here it is my URLEncoding. As I cannot use body or subject string in URL without encoding them, my output here is with "+" instead of whitespace. Which is normal, I understand that. I was thinking if there is a way to visualize subject and body normally in my message? I tried with .replace("+"," ") but it is not working as it is giving an error. This is how it is now:

enter image description here

I think there might be different character set but I am not sure.

1 Answers

0
Community On

That's the way URLEncoder works.

One possible approach would be to replace all + with %20 after URLEncoder.enocde(...) Or you could rely on URI constructor to encode your parameters correctly:

String scheme = "mailto";
        String recipient = "[email protected]";
        String subject = "The Meaning of Life";
        String content = "..., the universe and all the rest is 42.\n Rly? Just kidding. Special characters: äöü";
        String path = "";
        String query = "subject=" + subject + "&body=" + content;
        Desktop.getDesktop().mail(new URI(scheme, recipient, path, query, null));

Both solutions have issues: In the first approach, you might replace actual + signs, with the second, you'll have issues with & character.