用Java动态读取邮件

时间:2013-04-19 03:06:43

标签: java email refresh javax.mail

我有一个线程,每10秒钟在一个循环中检查我的收件箱。我在循环之前创建了我的邮件会话并存储并连接到商店

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

问题在于线程运行时没有收到新的电子邮件。

所以,我试图在循环中连接并关闭商店:

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
    }
}

第一个循环很好并且所有电子邮件都被正确接收但现在我在第二个 store.connect()上收到NullPointerException:

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]

我必须做什么才能在每个循环中刷新INBOX?

1 个答案:

答案 0 :(得分:0)

好吧,我自己弄清楚了。问题是我每次循环中时都必须从会话中检索商店:

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