我尝试实现一个邮件服务器,该服务器使用 sun IMAPFolder 和 idle 命令解析传感器发送的电子邮件。
不幸的是,空闲状态在 30 分钟后关闭并引发 FolderClosedException。为了模拟在空闲重新启动时电子邮件到达的最坏情况,我在异常正文中发送了一封测试电子邮件,并查看电子邮件是否被处理。
我的代码:
public void run() {
try {
Properties props = System.getProperties();
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.imap.timeout", "5000");
for(;;) {
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore("imap");
store.connect("localhost", "test@email.db.de", "testpw1");
Folder folder = store.getFolder("inbox");
if ((folder == null) || !folder.exists()) {
logger.error("folder -inbox- is invalid.");
return;
}
folder.open(Folder.READ_WRITE);
// Add messageCountListener to listen for new messages
folder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent event) {
Message[] messages = event.getMessages();
processMessages(messages);
}
});
logger.debug("idle start");
IMAPFolder f = (IMAPFolder) folder;
f.idle(); //idle state
} catch (FolderClosedException ex) {
logger.info("idle timeout");
long time = Calendar.getInstance().getTimeInMillis();
DateFormat df = DateFormat.getDateTimeInstance();
SendEmail.send("test@email.db.de", "TestSubject", "This mail is sent when idle is off" + df.format(new Date(time));
} catch (Exception ex) {
ex.printStackTrace();
}
}//endfor
} catch (Exception ex) {
ex.printStackTrace();
}
}
不幸的是,我得到了两个不同的输出,我不知道为什么。
有时会处理电子邮件:
02/25/2013 11:45:04.202 DEBUG [Thread-0] logger - idle start
02/25/2013 12:15:04.202 INFO [Thread-0] logger - idle timeout
This mail is sent when idle is off 25.02.2013 12:15:04
02/25/2013 12:15:04.235 DEBUG [Thread-0] logger - idle start
Got 1 new messages
02/25/2013 12:15:04.267 DEBUG [Thread-0] logger - idle start
有时不是:
02/25/2013 10:41:28.895 DEBUG [Thread-0] logger - idle start
02/25/2013 11:11:28.898 INFO [Thread-0] logger - idle timeout
This mail is sent when idle is off 25.02.2013 11:11:28
02/25/2013 11:11:28.962 DEBUG [Thread-0] logger - idle start
我的目标是不再抛出 folderClosedException 或始终处理捕获正文中的电子邮件。
我怎样才能做到这一点?为什么我这里有两种类型的输出?
提前致谢。