Search code examples
javaemailrefreshjakarta-mail

Reading mails dynamically in Java


I have a thread which checks my inbox in a loop every 10 seconds. I create my mail session and store and connect to the store before the loop:

store.connect()
while (running) {
    Thread.sleep(emailReceiveInterval);
    inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    Message[] emails = inbox.getMessages();
    [...]
    inbox.close(true);
}

The problem with that is that no new emails are picked up while the thread is running.

So, I have tried to connect and close to the store in the loop:

while (running) {
    try {
        Thread.sleep(emailReceiveInterval);
        store.connect();
        inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        Message[] emails = inbox.getMessages();
        [...]
    finally {
        inbox.close(true);  // Exception handling not posted
        store.close();      // Exception handling not posted
    }
}

The first loop is fine and all emails are received correctly but now I receive a NullPointerException on the second store.connect():

java.lang.NullPointerException: null
    at org.apache.geronimo.javamail.store.pop3.POP3Store.protocolConnect(POP3Store.java:164) ~[geronimo-javamail_1.4_mail-1.8.2.jar:1.8.2]
    at javax.mail.Service.connect(Service.java:251) ~[geronimo-javamail_1.4_mail-1.8.2.jar:1.8.2]
    at javax.mail.Service.connect(Service.java:91) ~[geronimo-javamail_1.4_mail-1.8.2.jar:1.8.2]
    at javax.mail.Service.connect(Service.java:76) ~[geronimo-javamail_1.4_mail-1.8.2.jar:1.8.2]
    at com.company.MyClass$ReceivingThread.run(MyClass.java:161) ~[target-eclipse/:na]

What do I have to do that the INBOX is refreshed on every loop?


Solution

  • Alright, I figured it out myself. The problem was that I also have to retrieve the store from the session every time within the loop:

    url = new URLName(mailProtocol, incomingHost, 995, "", incomingUserName,     incomingUserName);
    session.getStore(url)