Recipe 20.4 Accessing Email from a Servlet


Problem

You want to access and display the content of email in a servlet.

Solution

Use the JavaMail API and a method inside the servlet to handle and display the values of email messages.

Discussion

Fetching email messages using JavaMail and a servlet is a straightforward process:

  1. Import the javax.mail and javax.mail.internet packages at the top of the servlet source code.

  2. Inside the servlet's mail-fetching method, create a javax.mail.Session object to handle this mail session.

  3. Get a message store object (a javax.mail.Store ) from the session to represent the POP3 mail account.

  4. Connect to the Store using the connect( String host , String user , String password ) method of the Store object (there are overloaded versions of this method). The Store is designed to authenticate a user and connect with a mail server.

  5. Access the INBOX folder from the message store.

  6. Obtain any messages that folder contains as a Message[] type, then do whatever you want with each message, iterating through the array .

Example 20-4 fetches email messages by calling its handleMessages( ) method in the doGet( ) service method.

Example 20-4. A servlet that fetches email messages
 package com.jspservletcookbook;     import java.io.IOException; import java.io.PrintWriter; import java.util.Properties;  import javax.mail.*; import javax.mail.internet.*;  import javax.servlet.*; import javax.servlet.http.*;  public class MailAccessor 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>");             //This method accesses any email and displays the contents  handleMessages(request, out);  out.println("</body></html>");   }//doGet  private void handleMessages(HttpServletRequest request,     PrintWriter out) throws IOException, ServletException {            //Obtain user authentication information for a POP server,       //used to access email. This information is stored in a       //HttpSession object       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 = MailAccessor.DEFAULT_SERVER;            try {                     //basic check for null or empty user and password           if ((! check(user))  (! check(password)))             throw new ServletException(               "A valid username and password is required.");               Properties properties = System.getProperties( );           //Obtain default 'Session' for this interaction with            //a mail server           Session session = Session.getDefaultInstance(properties);           //Obtain a message store (i.e., a POP3 email account, from           //the Session object           popStore = session.getStore("pop3");               //connect to the store with authentication information           popStore.connect(popAddr, user, password);           //Get the INBOX folder, open it, and retireve any emails           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 doesn't contain any email "+             "messages.</h2>");}              //for each retrieved message, use displayMessage method to            //display the mail message           for (int i = 0; i < msgLen; i++){               displayMessage(messages[i], out);               out.println("<br /><br />");           }  } catch (Exception exc) {                out.println(             "<h2>Sorry, an error occurred while accessing the email" +             " messages.</h2>");            out.println(exc.toString( ));  } finally {           try{              //close the folder and the store in the finally block              //if 'true' parameter, any deleted messages will be expunged              //from the Folder              if (folder != null)                  folder.close(false);                    if (popStore != null)                  popStore.close( );           } catch (Exception e) { }       }   }//printMessages        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( ));       } else{                   out.println(             "<h2>The received email message was not of a text " +                 "content type.</h2>");               }//outer if             }//displayMessage  private boolean check(String value){            if(value == null  value.equals(""))           return false;                    return true;        }//check } 

The displayMessage( ) method displays each message's "from" address, the message's content type (i.e., the MIME type as in text/plain ), and the email's content. You can get the String from a typical email message that contains just headers and the text message by calling Message.getContent( ) . Getting the "from" address is a little trickier:

 out.println("Message received from: " +     ((InternetAddress)msg.getFrom( )[0]).getAddress( ) +"<br />"); 

The Message.getFrom( ) method returns an array of javax.mail.Address objects. This code is designed to access the first email address, since an email is typically sent by one party to its recipient (not including those malicious spammers, of course).

The code accesses the first array member, casts the return value to a javax.mail.InternetAddress , then calls getAddress( ) on that object, which returns the String email address.

Figure 20-1 shows the servlet's return value in a browser window. Since the servlet receives its email authentication information from session attributes, the first request targets a JSP, which sets the session attributes. Then the JSP forwards the request to the MailAccessor servlet. The servlet displays each received email separated by two line breaks. In other words, the information the servlet displays about each email includes who sent the email, the mail's content type, and the content of the message itself.

Figure 20-1. A servlet fetches and displays two email messages
figs/jsjc_2001.gif

See Also

Chapter 16 on setting session attributes; Chapter 25 on accessing a javax.mail.Session JNDI object on BEA WebLogic; 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 using a servlet; Recipe 20.3 on sending email using a JavaBean; 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

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