2010-12-06

A simple way of sending emails in Java: mailto links

Whenever I send automated emails, I prefer to have one last look at them, before sending them off. The following method allows one to do this, as all of the generated emails are opened in your default email program, complete with recipients, subject, and content. Thankfully, this is easy to do, by just sending a properly encoded URL to the operating system. Doing this depends on java.awt.Desktop and thus Java 6.

mailto: URL syntax

"mailto:" recipients ( "?" key "=" value ("&" key "=" value)* )?

Java source code

public static void mailto(List<String> recipients, String subject,
        String body) throws IOException, URISyntaxException {
    String uriStr = String.format("mailto:%s?subject=%s&body=%s",
            join(",", recipients), // use semicolon ";" for Outlook!
            urlEncode(subject),
            urlEncode(body));
    Desktop.getDesktop().browse(new URI(uriStr));
}

private static final String urlEncode(String str) {
    try {
        return URLEncoder.encode(str, "UTF-8").replace("+", "%20");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

public static final String join(String sep, Iterable<?> objs) {
    StringBuilder sb = new StringBuilder();
    for(Object obj : objs) {
        if (sb.length() > 0) sb.append(sep);
        sb.append(obj);
    }
    return sb.toString();
}

public static void main(String[] args) throws IOException, URISyntaxException {
    mailto(Arrays.asList("john@example.com", "jane@example.com"), "Hello!",
            "This is\nan automatically sent email!\n");
}
Related post:
  1. Generate emails with mailto URLs and Python

No comments: