<< How do I parse or format dates? Dates are hard! | Home | My data structures have changed - how can I migrate my data model? >>

How do I send mail with Java?

You send mail in Java with one of two APIs, basically: JavaMail and Commons-Email. People who use JavaMail fit in one of three categories: they don't know about Commons-Email, they are doing bulk mail and know what they're doing, or they're gluttons for punishment. SendMail.java is a class that shows how to send mail with both JavaMail and Commons-Email, for the case of sending to a single address.

It's very simple; it declares a Mailer interface, and then implements it for both JavaMail and Commons-Email.

The JavaMail version requires mail.jar and activation.jar in your classpath (see the JavaMail home page for details) and is 13 lines of code, basically; it goes through setting up a transport session, creating a message with the right activation types, and then sends the mail.

The Commons-Email version is much simpler, and makes more sense from an end-user's perspective: one doesn't normally care about the guts of sending mail via sessions, one just wants to send a freakin' email.

This highlights one of the common misperceptions about Java's base APIs: most of them are designed for correctness and flexibility, and the idea was that people would write libraries above them that focused on specific tasks done simply... but people tended to use the base APIs themselves, and since that's a bit of a pain, they associate the pain with Java as a whole.

BTW: as usual, one would use one class or interface per file, but for simplicity's sake, all of the classes for sending mail are in SendMail.java, with SendMail being the only public class.

Tags :


Re: How do I send mail with Java?

Personally I dreaded sending e-mail in Java until I started using Seam. In fairness, Spring supporters could say the same thing about their framework. jBPM is yet another interface. Those are the APIs to the mail you are calling for.

I would discourage anyone from using yet another homegrown wrapper around the JavaMail API and instead use e-mail support from their framework. I even consider the commons-email a bit too one-offish. For instance, in Seam you can compose e-mails using XHTML templates. To me, that is the type of ease one should have when composing an email. Reason being that email is probably the most ubiqutous technology.

Re: How do I send mail with Java?

Those are actually good points, Dan, but most people aren't using Seam yet - so the point of contact is still "how do I send the email" and not "how do I compose the email and let the framework send it." But don't let that stand in the way of a very valid point, folks: if you're using a framework that supports sending mail for you, by all means, use it.

Re: How do I send mail with Java?

http://www.javacommerce.com/displaypage.jsp?name=javamail.sql&id=18274

Add a comment Send a TrackBack