Over a million developers have joined DZone.

A Simple Way of Sending Emails in Java: mailto Links

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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. If you want to do this in Python then this blog post shows you how.

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");
}

From http://2ality.blogspot.com/2010/12/simple-way-of-sending-emails-in-java.html

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}