Markus
Markus

Reputation: 1482

Java: Send e-mail with default mail client: How to make new lines?

I'm opening the default mail client with a pre filled form (to, subject, body).

Everything works fine except for one thing. I can't figure out out to add a linebreak to the body text. I tried to encode the <br> Tag but it didn't work. The result was that in the body only showed the first line while the second line was gone.

Example:

private void openMail(URI uri) {
        if (Desktop.isDesktopSupported() && (Desktop.getDesktop()).isSupported(Desktop.Action.MAIL)) {
            try {
                try {
                    String address = "[email protected]";
                    String subject = "Custom_Subject";
                    String html_br = "&lt;br&gt;";
                    String body = "First%20Line" + html_br + "Second%20Line";
                    String mailToString = "mailto:" + address + "?subject=" + subject + "&body=" + body;

                    URI mailto = new URI(mailToString);
                    Desktop.getDesktop().mail(mailto);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
            }
        } else {

        }
    }

Upvotes: 1

Views: 953

Answers (2)

Adrian Kubitza
Adrian Kubitza

Reputation: 11

If the format is HTML newline characters will be ignored and you'd need to insert HTML breaks <br />.

StringBuilder body = new StringBuilder();
body.append("First Line<br />");
body.append("Second Line<br />");
String mailToString = "mailto:" + address + "?subject=" + subject + "&body=" + body.toString();

Upvotes: 0

Jens
Jens

Reputation: 69440

Try %0D%0A (as carrage return linefeed)

Upvotes: 3

Related Questions