A Simple Way of Sending Emails in Java: mailto Links
Join the DZone community and get the full member experience.
Join For FreeWhenever 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)* )?
- recipients: comma-separated email addresses
- value: should be URL-encoded (e.g. space becomes %20)
- key: subject, cc, bcc, body
- Example: mailto:joe@example.com?subject=hello&body=How%20are%20you%3F
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
Opinions expressed by DZone contributors are their own.
Comments