Sending Email

Sometimes it’s necessary, or just convenient, for a servlet to fire off an email message. For example, imagine a servlet that receives data from a user feedback form. The servlet might want to send the feedback data to a mailing list of interested parties. Or imagine a servlet that encounters an unexpected problem and knows to send an email page to its administrator asking for help.

A servlet has four choices for sending email:

  • It can manage the details itself—establishing a raw socket connection to a mail server and speaking a low-level mail transport protocol, usually the so-called Simple Mail Transfer Protocol (SMTP).

  • It can run on external command-line email program, if the server system has such a program.

  • It can use the new JavaMail API, designed to support complicated mail handling, filing, and processing (see http://java.sun.com/products/javamail ).

  • It can use one of the many freely available mail classes that abstracts the details of sending email into simple, convenient method calls.

For most servlets, we recommend the final approach for its simplicity.

Using sun.net.smtp.SmtpClient

For the purposes of this example, we’ll demonstrate a servlet that uses the sun.net.smtp.SmtpClient class. It’s conveniently provided with Sun’s JDK and most JVMs descended from it, but we should warn you that it’s unsupported and subject to change (though it hasn’t changed since JDK 1.0). Using it is simple:

  1. Call SmtpClient smtp = new SmtpClient(). Optionally, pass the constructor ...

Get Java Servlet Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.