[ Team LiB ] Previous Section Next Section

Recipe 20.8 Reading a Received Email's Headers from a Servlet

Problem

You want to read the headers from an email in a servlet.

Solution

Use the JavaMail API to access each email message. Call the getAllHeaders( ) method of the Part interface, then iterate through the Enumeration return value to get the name and value of each header.

Discussion

An advanced email program, such as a spam filter, is designed to examine an email's headers, not just its message and file attachments.

A header is composed of a name, a colon character (:), and a value. The headers provide details about the email message, such as who sent the message and the mail server(s) that handled the message during its network travels. An example header is:

To: <bwperry@parkerriver.com>

The JavaMail API makes it easy to list an email's headers. The Message object has a getAllHeaders( ) method (via the Part interface that the Message class implements). This method returns a java.util.Enumeration, holding a collection of javax.mail.Header objects. To get the header name and value from these Header objects, just call their getName( ) and getValue( ) methods.

The Part interface also has a getHeader(String headerName) method that you can use to obtain the value for a particular header. This method returns a String array containing the value(s) for the header of that name.


Example 20-9 shows the same servlet from Recipe 20.4, revised to list both the message contents and the header values. The header-related code appears in the displayMessage( ) method.

Example 20-9. A servlet displays email header names and values
package com.jspservletcookbook;    

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Properties;
import java.util.Enumeration;

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderAccessor extends HttpServlet {

   private final static String DEFAULT_SERVER = "mail.attbi.com";

  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 Reader</title></head><body>");
     
     handleMessages(request, out);
    
     out.println("</body></html>");
  } //doGet
     
  private void handleMessages(HttpServletRequest request,
      PrintWriter out) throws IOException, ServletException {
    
      HttpSession httpSession =  request.getSession( );
      String user = (String) httpSession.getAttribute("user");
      String password = (String) httpSession.getAttribute("pass");
      String popAddr = (String) httpSession.getAttribute("pop");
      Store popStore = null;
      Folder folder = null;
   
      if (! check(popAddr))
          popAddr = HeaderAccessor.DEFAULT_SERVER;
    
      try {
   
         if ((! check(user)) || (! check(password)))
             throw new ServletException(
             "A valid username and password is required to check email.");
   
          Properties properties = System.getProperties( );
          Session session = Session.getDefaultInstance(properties);
          popStore = session.getStore("pop3");
          popStore.connect(popAddr, user, password);
          folder = popStore.getFolder("INBOX");
          if (! folder.exists( ))
              throw new ServletException(
              "An 'INBOX' folder does not exist for the user.");
       
          folder.open(Folder.READ_ONLY);
          Message[] messages = folder.getMessages( );
          int msgLen = messages.length;
  
         if (msgLen == 0)
             out.println(
             "<h2>The INBOX folder does not yet contain any " +
             "email messages.</h2>");
  
         for (int i = 0; i < msgLen; i++){

             displayMessage(messages[i], out);
             out.println("<br /><br />");

         }//for
   
    } catch (Exception exc) {
    
        out.println(
          "<h2>Sorry, an error occurred while accessing the " +
          "email messages.</h2>");
        out.println(exc.toString( ));
        
    } finally {

        try{

            if (folder != null)
                folder.close(false);
            
            if (popStore != null)
               popStore.close( );

        } catch (Exception e) { }
    }
  }//handleMessages
    
  private void displayMessage(Message msg, PrintWriter out) 
      throws MessagingException, IOException{
    
      if (msg != null && msg.getContent( ) instanceof String){
         
          if (msg.getFrom( )[0] instanceof InternetAddress){

              out.println(
              "Message received from: " +
              ((InternetAddress)msg.getFrom( )[0]).getAddress( ) +"<br />");
         }
         out.println("Message content type: " + msg.getContentType( ) +
           "<br />");
         out.println(
           "Message body content: " + (String) msg.getContent( ));

         //List each of the email headers using a ul tag
         out.println("<ul>");
         Header head = null;
         Enumeration headers = msg.getAllHeaders( );
         
         while ( headers.hasMoreElements( ) ){
             head = (Header) headers.nextElement( );
             out.println(
               "<li>" + head.getName( ) + ": " + head.getValue( )+ "</li>");
         }//while

          out.println("</ul>");
         
      } else{
       
           out.println(
            "<h2>The received email message was not " +
            "a text content type.</h2>");
      }
         
  }//displayMessage
    
  private boolean check(String value){
    
      if(value == null || value.equals(""))
      return false;
            
      return true;
    }
}

Figure 20-3 shows the browser display of the servlet in Example 20-9. Each of the headers is preceded by a bullet character, followed by the header name, a colon, and the header value.

Figure 20-3. A servlet accesses an email and displays its header s
figs/jsjc_2003.gif

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.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.

    [ Team LiB ] Previous Section Next Section