我有以下代碼,我想通過批量檢索(例如:獲取前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