I am trying to listen for new messages using the POP3 protocol. I am aware that Pop3 doesn't allow new messages to appear in the Inbox while the folder is open. Below is the code that I have implemented:
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
public class EmailListener extends MessageCountAdapter {
public EmailListener() {
}
public void messagesAdded(MessageCountEvent e) {
System.out.println("I");
}
public void messagesRemoved(MessageCountEvent e) {
System.out.println("J");
}
}
public class POPReceiver {
public POPReceiver() {
}
public void listen() throws Exception {
Properties properties = new Properties();
Session session = null;
POP3Store pop3Store = null;
String host = "NB-EX101.example.com";
String user = "user2";
properties.put(mail.pop3.host, host);
session = Session.getDefaultInstance(properties);
pop3Store = (POP3Store) session.getStore("pop3");
pop3Store.connect(user, "password");
Folder folder = pop3Store.getFolder("INBOX");
folder.addMessageCountListener(new EmailListener());
sendEmail();
}
public void sendEmail() {
// not added code, but the email sends
}
}
public static void main(String[] args) throws Exception {
POPReceiver i = new POPReceiver();
i.listen();
}
I am using Microsoft Exchange Server. Any ideas why it is not listening?
I have looked on http://www.coderanch.com/t/597347/java/java/Email-Listener but still does not listen.
From Javamail FAQ (http://www.oracle.com/technetwork/java/javamail/faq/index.html):
Q: I set up a MessageCountListener
(as demonstrated in the monitor program) but I'm never notified of new mail in my POP3 INBOX.
A: The POP3 protocol does not allow the client to see new messages delivered to the INBOX while the INBOX is open. The application must close the INBOX and reopen it in order to see any new messages. You will never be notified of new mail using the MessageCountListener
interface with POP3. See the com.sun.mail.pop3
package documentation for more information.
So, MessageCountListener
will not work for POP3. You'll need to implement polling to get information about new messages for POP3.
However, you can try using IMAP instead.
But even in the case of IMAP you should be using this in another way. See idle()
method in IMAPStore
class (e.g. being called in a loop in a separate thread etc - see https://javamail.java.net/nonav/docs/api/com/sun/mail/imap/IMAPStore.html#idle() ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With