Java Servlet & JSP Cookbook

Problem

You want to use a JavaBean or helper class to access and display email messages.

Solution

Add the handleMessages( ) and displayMessage( ) methods from Example 20-4 to the JavaBean class defined in Example 20-2. Then use the JavaBean from a servlet's doGet( ) or doPost( ) method.

Discussion

When we last encountered the EmailBean in Example 20-2 it contained a sendMessage( ) method, along with several property "setter" methods (such as setSmtpHost(String host) ). If you add the handleMessages( ) and displayMessage( ) methods from Example 20-4 to this same class, you can use the JavaBean to both send and access email.

This code in handleMessages( ) from Example 20-4 needs to be changed to include the EmailBean class name :

//static reference to a constant value if (! check(popAddr)) popAddr = EmailBean.DEFAULT_SERVER;

However, the EmailBean class will have grown quite large as a result of adding the two methods, so you might create two JavaBeans ”one for sending mail and another for accessing it. Example 20-5 creates and uses an instance of a special email JavaBean. You must store the bean class in the WEB-INF/classes directory or in a JAR file in WEB-INF/lib .

Example 20-6 also shows a JavaBean that defines handleMessages( ) and displayMessage( ) for dealing with email attachments.

Example 20-5. A servlet uses a JavaBean to access email messages

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); out.println( "<html><head><title>Email message sender</title></head><body>"); EmailBean emailer = new EmailBean( ); emailer.setSmtpHost("mail.attbi.com"); emailer.handleMessages(request,out); out.println("</body></html>"); }//doGet

See Also

Sun Microsystem's JavaMail API page: http://java.sun.com/products/javamail/; Recipe 20.1 on adding JavaMail- related JARs to your web application; Recipe 20.2 on sending email from a servlet; Recipe 20.3 on sending email using a JavaBean; Recipe 20.4 covering how to access email in a servlet; 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.

Категории