如何使用IMAP和JavaMail更快地从GMAIL下载电子邮件? 我可以使用IMAP进行批量下载吗? 我也将电子邮件保存到MongoDB中。 我看到一些网站正在迅速做到这一点。
// Get inbox folder
Folder inbox = store.getFolder("inbox");
// SET readonly format (*You can set read and write)
inbox.open(Folder.READ_ONLY);
// Display email Details
// Inbox email count
int messageCount = inbox.getMessageCount();
System.out.println("Total Messages in INBOX:- " + messageCount);
Message[] messages = inbox.getMessages(1, messageCount);
long startTime = System.currentTimeMillis();
// Fetch only necessary headers for each message
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
profile.add(FetchProfile.Item.FLAGS);
profile.add(FetchProfile.Item.CONTENT_INFO);
if (inbox instanceof UIDFolder) {
profile.add(UIDFolder.FetchProfileItem.UID);
}
inbox.fetch(messages, profile);
System.out
.println("Time elapsed while fetching message headers;" + (System.currentTimeMillis() - startTime));
ArrayList<Email> al = new ArrayList<Email>();
for (int i = 1; i < messageCount; i++) {
//System.out.println("------------------------------------------------------------");
Email email = new Email();
email.setId(i + "");
email.setSenderAddress(extractEmail(messages[i].getFrom()[0].toString()));
email.setReceivedDate(messages[i].getReceivedDate());
email.setSentDate(messages[i].getSentDate());
email.setSubject(messages[i].getSubject());
email.setMessageContent(messages[i].getContent().toString());
email.setReceiverAddresses(new String[messages[i].getAllRecipients().length]);
for (int j = 0; j < messages[i].getAllRecipients().length; j++)
email.getReceiverAddresses()[j] = extractEmail(
messages[i].getAllRecipients()[j].toString());
al.add(email);
if (i % 2000 == 0) {
emailMongoRepository.save(al);
System.out.println("----------Bulk Save--------------------------------------------------");
al = new ArrayList<Email>();
}
}
inbox.close(true);
store.close();
System.out.println("Time elapsed while fetching message headers;" + (System.currentTimeMillis() - startTime));
} catch (Exception e) {
e.printStackTrace();
}