我有以下代码,我想批量检索(例如:获取前 50 条消息,处理它,然后获取下 50 条)。目前它获取所有消息并将其存储在一个数组中。Javamail 支持吗?如果不是如何批量检索?
感谢您的回答。
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect(host, userName, password);
Folder inbox = null;
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
for (int i = 0; i < messages.length; i++)
{
//Process a message
}
更新:
我试图按如下方式实现批处理,但它没有按预期工作。
问题是:
假设收件箱中有 24 封电子邮件,然后
totalUnread
显示正确,但Message[] messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false), inbox.getMessages(batchStart, batchEnd));
只返回 5 条记录,而不是 10 条记录,因为BATCH_SIZE
IS 10。另一个问题是即使被调用,已处理的电子邮件也没有标记为已读
getContent()
。private static final int BATCH_SIZE = 10; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); AuthenticationService authenticationService = null; Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect(host, userName, password); Folder inbox = null; inbox = store.getFolder("Inbox"); int totalUnread = inbox.getUnreadMessageCount(); if (totalUnread != 0) { inbox.open(Folder.READ_WRITE); int batchStart = 1; int batchEnd = (totalUnread > BATCH_SIZE ? BATCH_SIZE : totalUnread); int batchCount = 0; while (true) { processABatch(inbox, batchStart, batchEnd, batchCount); batchStart = batchEnd + 1; if (batchStart > totalUnread) { break; } batchEnd = ((batchEnd + BATCH_SIZE) < totalUnread ? (batchEnd + BATCH_SIZE) : totalUnread); batchCount++; } } inbox.close(true); store.close(); } private void processABatch(Folder inbox, int batchStart, int batchEnd, int batchCount) throws MessagingException { Message[] messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false), inbox.getMessages(batchStart, batchEnd)); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.CONTENT_INFO); inbox.fetch(messages, fp); for (int i = 0; i < messages.length; i++) { processMessage(messages[i], inbox); } }