8 Replies Latest reply: Apr 11, 2012 12:54 PM by Bshannon-Oracle RSS

    Fetching email with attachments in Tomcat

    928796
      I'm trying to process emails with attachments using following code and it works fine in standalone java application, but when I run this code on Tomcat it treates all messages as not multipart. Class of all contents got from messages is SharedByteArrayInputStream.
      I'm using jdk1.6.0_27 and javamail1_4_5
      I put mail.jar in WEB-INF/lib of my war.

      Can anyone help my how to deal with this? What's wrong?



      package test;
      import java.util.Arrays;
      import java.util.List;
      import java.util.Properties;
      import javax.mail.Folder;
      import javax.mail.Message;
      import javax.mail.MessagingException;
      import javax.mail.Multipart;
      import javax.mail.Session;
      import javax.mail.Store;
      public class Main {
      private static Store store;
      private static Folder folder;
      /**
      * @param args
      * @throws Exception
      */
      public static void main(String[] args) throws Exception {
      try {
      List<Message> messages = getMessages("...", "...", "...");
      for (Message mess : messages) {
      System.out.println(mess.getSentDate());
      Object content = mess.getContent();
      if (content instanceof Multipart) {
      System.out.println("miltipart");
      } else {
      System.out.println("plain");
      }
      }
      } finally {
      close();
      }
      }
      public static List<Message> getMessages(String host, String userName, String password) throws Exception {
      if (store != null || folder != null) {
      throw new IllegalStateException("There are open and closed messages exist");
      }
      // create empty properties
      Properties props = new Properties();
      // get session
      Session session = Session.getDefaultInstance(props, null);
      try {
      // get the store
      store = session.getStore("pop3");
      store.connect(host, userName, password);
      // get folder
      folder = store.getFolder("INBOX");
      folder.open(Folder.READ_ONLY);
      // get directory
      return Arrays.asList(folder.getMessages());
      } catch (MessagingException e) {
      throw new Exception("Exception while mail receiving ", e);
      }
      }
      public static void close() throws MessagingException {
      // close connection
      if (folder != null) {
      folder.close(false);
      }
      if (store != null) {
      store.close();
      }
      folder = null;
      store = null;
      }
      }