Over a million developers have joined DZone.

A Simple Way of Sending Emails in Java: mailto Links

DZone's Guide to

A Simple Way of Sending Emails in Java: mailto Links

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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!
    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);
    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

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}