我对javamail的使用感到困惑。我需要不时从邮件服务器下载最新的电子邮件,但javamail似乎无法在小时,分钟和秒内查询特定邮件,只有一天可用?
(1)我应该扫描所有回复电子邮件,以便在时间间隔内进行额外检查吗?或者我做错了什么?
(2)我是否应该通过receivedDate按升序排列电子邮件,并安全地忽略电子邮件的顶部(假设以前已经检索过)
(3)任何推荐的扫描间隔?如果与邮件客户端比较怎么办?
private void retrieveEmailsWithinDateInterval() throws ParseException, MessagingException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 1);
//Retrieval of email setting
Date previousDate = sdf.parse("2018-02-13");
Date tmrDate = new Date(c.getTimeInMillis());
String imapHost = "***";
int port = 587;
String urlNameStr = "***";
String emailAddr = "***";
String emailPass = "***";
String inboxFolderName = "***";
Properties props = System.getProperties();
props.setProperty("mail.imap.host", imapHost);
props.setProperty("mail.imap.port", Integer.toString(port));
props.setProperty("mail.store.protocol", "imap");
Session session = Session.getDefaultInstance(props, null);
URLName urlName = new URLName(urlNameStr);
Store store = session.getStore(urlName);
store.connect(imapHost, emailAddr, emailPass);
ReceivedDateTerm minDateTerm = new ReceivedDateTerm(ComparisonTerm.GT, previousDate);
ReceivedDateTerm maxDateTerm = new ReceivedDateTerm(ComparisonTerm.LT, tmrDate);
SearchTerm searchTerm = new AndTerm(minDateTerm, maxDateTerm);
IMAPFolder inboxFolder = (IMAPFolder) store.getFolder(inboxFolderName);
if(!inboxFolder.isOpen())
inboxFolder.open(Folder.READ_ONLY);
Message[] messagesInbox = inboxFolder.search(searchTerm);
for (Message msg : messagesInbox){
//(1) Should I extra check or alternative solution?
//Seem it compare date only and ignore hour, minute and second.
if (msg.getReceivedDate().getTime() <= previousDate.getTime())
continue;
//(2) Should I scan through email messages?
//Or will all mail server sort in receivedDate, that I can safely ignore top messages or bottom messages?
processEmailWithinDatetimeInterval(msg);
}
if ((inboxFolder != null) && inboxFolder.isOpen()) {
inboxFolder.close(true);
}
if (store != null) {
store.close();
}
}
答案 0 :(得分:0)
IMAP协议的限制是您只能按天搜索,而不是按时间搜索。
如果您只想在INBOX中找到之前未见过的最新消息,可以keep track of the UID of the last message you've seen然后ask for messages with larger UIDs,例如
Message[] newMessages = ((UIDFolder)folder).getMessagesByUID(lastSeen + 1, UIDFolder.MAXUID);