Recipe 20.2 Sending Email from a Servlet


You want to send emails from a servlet.


Import the javax.mail and javax.mail.internet packages at the top of the servlet source code. Create a sendMessage( ) method (or a method with a different name ) that can be called from the servlet methods doGet( ) or doPost( ) .


The sendMessage( ) method in Example 20-1 uses the JavaMail API to connect with a mail server, construct an email message, and then send that message to one or more recipients. The servlet obtains the various components of an email ”the target email address, the sender's address, the subject field, and the email's body content ”from request parameters. The servlet can handle a form submitted by a client using a web browser.

The form tag might look like this:

 <form method="POST" action= "/home/servlet/com.jspservletcookbook.EmailServlet"> 

Example 20-1 calls the sendMessage( ) method from the service method doPost( ) . The sendMessage( ) method parameters comprise the parts of an email: the SMTP server, the recipient of the email (the variable to ), the "from" address of the sender, the email subject, and the email's content.

Example 20-1. A servlet sends email based on request parameter values
 package com.jspservletcookbook;     import; import; import java.util.Properties;  import javax.mail.*; import javax.mail.internet.*;  import javax.servlet.*; import javax.servlet.http.*;  public class EmailServlet extends HttpServlet {  //default value for mail server address, in case the user     //doesn't provide one    private final static String DEFAULT_SERVER = "";   public void doPost(HttpServletRequest request,      HttpServletResponse response) throws ServletException, {  //obtain the values for email components from       //request parameters       String smtpServ = request.getParameter("smtp");       if (smtpServ == null  smtpServ.equals(""))           smtpServ = DEFAULT_SERVER;              String from = request.getParameter("from");       String to = request.getParameter("to");       String subject = request.getParameter("subject");       String emailContent = request.getParameter("emailContent");  response.setContentType("text/html"); out = response.getWriter( );       out.println(         "<html><head><title>Email message sender</title></head><body>");             try {  sendMessage(smtpServ, to, from, subject, emailContent);  } catch (Exception e) {                    throw new ServletException(e.getMessage( ));                     }                out.println(             "<h2>The message was sent successfully</h2>");             out.println("</body></html>");   } //doPost  private void sendMessage(String smtpServer, String to, String from,     String subject,String emailContent) throws Exception {             Properties properties = System.getProperties( );       //populate the 'Properties' object with the mail       //server address, so that the default 'Session'       //instance can use it.       properties.put("", smtpServer);       Session session = Session.getDefaultInstance(properties);       Message mailMsg = new MimeMessage(session);//a new email message       InternetAddress[] addresses = null;  try {               if (to != null) {  //throws 'AddressException' if the 'to' email address               //violates RFC822 syntax               addresses = InternetAddress.parse(to, false);               mailMsg.setRecipients(Message.RecipientType.TO, addresses);  } else {                        throw new MessagingException(                 "The mail message requires a 'To' address.");                    }           if (from != null) {  mailMsg.setFrom(new InternetAddress(from));  } else {                        throw new MessagingException(                 "The mail message requires a valid 'From' address.");                    }  if (subject != null)               mailMsg.setSubject(subject);           if (emailContent != null)               mailMsg.setText(emailContent);                    //Finally, send the mail message; throws a 'SendFailedException'            //if any of the message's recipients have an invalid address           Transport.send(mailMsg);  } catch (Exception exc) {                     throw exc;                }         }//sendMessage        public void doGet(HttpServletRequest request,        HttpServletResponse response) throws ServletException,  {                          //doGet( ) calls doPost( )...       doPost(request, response);   }//doGet      }//EmailServlet 

The servlet interacts with a mail server in the following manner:

  1. The code creates a javax.mail.Session object, which contains various defaults and property values (such as ) that the other JavaMail objects will use. You can share a single Session object in an application.

  2. The code creates a MimeMessage object (passing in the Session as a constructor parameter).

  3. The servlet then populates the MimeMessage with an email's various components, such as the "to" and "from" email addresses, the email subject, as well as the message content.

  4. The code sends the email using the javax.mail.Transport static send( ) method.

See Also

The Sun Microsystems JavaMail API page:; Recipe 20.1 on adding JavaMail- related JARs to your web application; Recipe 20.3 on sending email using a JavaBean; Recipe 20.4 covering how to access email in a servlet; Recipe 20.5 on accessing email with a JavaBean; Recipe 20.6 on handling attachments in a servlet; Recipe 20.7 on adding attachments to an email message; Recipe 20.8 on reading an email's headers.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: