Java Email Folder get message

Description

Java Email Folder get message

import java.io.IOException;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class Main {

   public static void main(String[] args) {

      Properties properties = new Properties();
      String username = "username";
      String password = "password";
      String folder = "Inbox";
      String host = "imap.host.com";

      try {//w  w  w  .  j a  v a  2  s. c o  m
         Session session = Session.getDefaultInstance(properties, null);
         Store store = session.getStore("imap");
         store.connect(host, username, password);
         System.out.println(store);
         Folder inbox = store.getFolder(folder);
         inbox.open(Folder.READ_WRITE);
         int messageCount = inbox.getMessageCount();
         int startMessage = messageCount - 10;
         if (startMessage < 1)
            startMessage = 1;
         Message messages[] = inbox.getMessages(startMessage, messageCount);
         for (Message message : messages) {
            boolean hasBeenRead = false;
            for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
               if (flag == Flags.Flag.SEEN) {
                  hasBeenRead = true;
                  break;
               }
            }
            message.setFlag(Flags.Flag.SEEN, false);
            System.out.println(message.getSubject() + " " + (hasBeenRead ? "(read)" : "") + message.getContent());

         }
         inbox.close(true);
      } catch (MessagingException | IOException e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related