19.2 Sending Email

Java Servlet Programming, 2nd Edition > 19. Odds and Ends > 19.2 Sending Email

 
< BACKCONTINUE >

19.2 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 an external command-line email program, if the server system has such a program.

  • It can use the 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 simple email sending, we recommend the final approach for its simplicity. For more complicated uses, we recommend JavaMail especially for servlets running inside a J2EE server where the two JAR files needed by JavaMail are sure to be available.

19.2.1 Using the MailMessage Class

For the purposes of this example, we will demonstrate a servlet that uses the com.oreilly.servlet.MailMessage class, which is not shown here but available at http://www.servlets.com. It is modeled after the sun.net.smtp.SmtpClient class provided with Sun's JDK but can be used without the political problem of using an "unsupported and subject to change" sun.* class. It also has a few nice usability improvements. Using it is simple:

  1. Call MailMessage msg = new MailMessage( ). Optionally, pass the constructor the name of a host to use as the mail server, which replaces the default of localhost. Most Unix machines can act as SMTP mail servers.

  2. Call msg.from(fromAddress), specifying the address of the sender. The address doesn't have to be valid.

  3. Call msg.to(toAddress), specifying the address of the receiver. This method may be called multiple times if there are additional recipients. There are cc( ) and bcc( ) methods as well.

  4. Call msg.setSubject(subject) to set the subject. Technically this isn't required, but providing a subject is always a good idea.

  5. Call msg.setHeader(name, value) if there are any additional headers to be set. The To:, Cc:, and Subject: headers don't need to be set as they are assigned automatically in the to( ), cc( ), and setSubject( ) methods. (The bcc( ) method of course doesn't set any headers.) You can use setHeader( ) to override the defaults. The header names and values should conform to the rules given in RFC 822 at http://www.ietf.org/rfc/rfc0822.txt.

  6. Call PrintStream msg = msg.getPrintStream( ) to get an output stream for the message.

  7. Write the body of the mail message to the PrintStream.

  8. Call msg.sendAndClose( ) to send the message and close the connection to the server.

19.2.2 Emailing Form Data

Example 19-3 shows a servlet that emails the form data it receives to a mailing list. Notice the extensive use of the ParameterParser class.

Example 19-3. Sending Mail from a Servlet
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import com.oreilly.servlet.MailMessage; import com.oreilly.servlet.ParameterParser; import com.oreilly.servlet.ServletUtils; public class MailServlet extends HttpServlet {   static final String FROM = "MailServlet";   static final String TO = "feedback-folks@attentive-company.com";   public void doGet(HttpServletRequest req, HttpServletResponse res)                                throws ServletException, IOException {     res.setContentType("text/plain");     PrintWriter out = res.getWriter();     ParameterParser parser = new ParameterParser(req);     String from = parser.getStringParameter("from", FROM);     String to = parser.getStringParameter("to", TO);     try {       MailMessage msg = new MailMessage();  // assume localhost       msg.from(from);       msg.to(to);       msg.setSubject("Customer feedback");       PrintStream body = msg.getPrintStream();       Enumeration enum = req.getParameterNames();       while (enum.hasMoreElements()) {         String name = (String)enum.nextElement();         if (name.equals("to") || name.equals("from")) continue; // Skip to/from         String value = parser.getStringParameter(name, null);         body.println(name + " = " + value);       }       body.println();       body.println("---");       body.println("Sent by " + HttpUtils.getRequestURL(req));       msg.sendAndClose();       out.println("Thanks for the submission...");     }     catch (IOException e) {       out.println("There was a problem handling the submission...");       log("There was a problem sending email", e);     }   } }

This servlet first determines the "from" and "to" addresses for the message. The default values are set in the FROM and TO variables, although a submitted form can include (probably hidden) fields that specify alternate from and to addresses. The servlet then begins an SMTP email message. It connects to the local host and addresses the message. Next, it sets the subject and fills the body with the form data, ignoring the TO and FROM variables. Finally, it sends the message and thanks the user for the submission. If there's a problem, it informs the user and logs the exception.

The MailMessage class does not currently support attachments (although support could easily be added). For more advanced uses such as this, JavaMail is a good alternative.


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net