我有以下代码,我想通过批量检索(例如:获取前50封邮件,处理它,然后获取下一个50)。目前它提取所有消息并将其存储在一个数组中。Javamail是否支持该消息?如果不是如何批量检索?使用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
}
UPDATE:
我试图实现配料如下,但预期它不工作。
的问题是:
假设有24的电子邮件收件箱中,然后
totalUnread
正显示出正确的,但Message[] messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false), inbox.getMessages(batchStart, batchEnd));
正在返回的只有5个而不是10个记录为BATCH_SIZE
为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); } }
由于'getMessages(start,end)'应用于完整的收件箱,而不是只检索未读邮件的当前过滤器,所以它看起来像建议的方法不起作用。除阅读全部(阅读和未阅读)电子邮件并批量阅读外,还有其他任何可能性吗? – Mahendran 2013-04-09 11:41:06
我已根据您的其他问题更新了原始答案。 – mthmulders 2013-04-09 12:06:07