Java email listener

坚强是说给别人听的谎言 提交于 2020-06-16 18:40:55

问题


I came across the IdleManager class and the watch method, which keeps the imap folder open and is in theory watching for new messages, but how do I get it to output or notify when a new email arrives?

The code:

public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;

    try 
    {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imaps.usesocketchannels", "true");

      Session session = Session.getDefaultInstance(props, null);

      ExecutorService es = Executors.newCachedThreadPool();
      final IdleManager idleManager = new IdleManager(session, es);

      store = session.getStore("imaps");
      store.connect("<mail>.com","<username>", "<password>");

      folder = (IMAPFolder) store.getFolder("INBOX"); 


      if(!folder.isOpen())
      folder.open(Folder.READ_ONLY);

      folder.addMessageCountListener(new MessageCountAdapter() {
          public void messagesAdded(MessageCountEvent ev) {
              Folder folder = (Folder)ev.getSource();
              Message[] msgs = ev.getMessages();
              System.out.println("Folder: " + folder +
                  " got " + msgs.length + " new messages");
              try {
                  // process new messages
                  idleManager.watch(folder); // keep watching for new messages
              } catch (MessagingException mex) {
                  // handle exception related to the Folder
              }
          }
      });
      idleManager.watch(folder);


      Message[] messages = folder.getMessages();
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println(messages.length);


      for (int i=0; i < messages.length;i++) 
      {

        System.out.println("*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg =  messages[i];

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
       System.out.println("To: "+msg.getAllRecipients()[0]);

      }
    }
    finally 
    {
      if (folder != null && folder.isOpen()) { folder.close(true); }
      if (store != null) { store.close(); }
    }

}

This code only gets and outputs the messages that were already in the folder, but it doesn't output new incoming emails.

How do I get it to output or notify new incoming emails?

来源:https://stackoverflow.com/questions/60093386/java-email-listener

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!