Using standard spec IMAP 开发者_C百科commands, how can I determine the previous and next UIDs in a mailbox based on a passed UID, sorting the mailbox messages by date, newest first?
I have found new mail UID with below code.
@Override
public void messagesAdded(MessageCountEvent e) {
try {
long newMailUID = ((IMAPFolder) e.getSource()).getUIDNext()
} catch (MessagingException e1) {
e1.printStackTrace();
}
}
Assuming that "sorting the mailbox messages by date, newest first" refers to the time the messages were added to the mailbox rather than INTERNALDATE
or the Date
header:
A001 SEARCH UID 82342
* SEARCH 83
A001 OK SEARCH completed
A002 FETCH 82,84 UID
* FETCH 82 (UID 82309)
* FETCH 84 (UID 82343)
A002 OK FETCH completed
Things to look out for:
- If the UID doesn't exist in the mailbox,
SEARCH
will return no results. - If the UID matched the first/last message in the mailbox, don't try to fetch the one before/after or you'll get a
BAD
response.
If you'd prefer not to use SEARCH
, you could also do the UID-to-sequence via UID FETCH
:
A001 UID FETCH 82342 UID
* FETCH 83 (UID 82342)
A001 OK UID FETCH completed
I think the only way would be to ask for all UIDs first:
UID SEARCH ALL
...and sort. Each message added to the mailbox is assigned a higher UID than the messages which were added previously.
So higher UID = newer email.
If you want to search for the UID before 12345, this command will do it:
a UID SEARCH RETURN (MAX) UID 1:12344
Finding the next after:
b UID SEARCH RETURN (MIN) UID 12346:*
This requires the ESEARCH extension, which most modern servers implement. Notably gmail implements it. It's a little too expensive to issue in a loop, though, so perhaps you're better off solving your issue in another way. Here's a two-command sequence to get the 50 UIDs immediately preceding 12345:
c1 SEARCH UID 12345
* SEARCH 1000
c1 OK done
c2 UID SEARCH 950:999
* SEARCH 12200,12202,...
c2 OK done
950 is "result of c1 - 50", 999 is "result of c1 - 1".
I'm not familiar with the exact commands, but have you checked out the RFC?
https://www.rfc-editor.org/rfc/rfc3501
Looks like there is a UIDNEXT command you can send that gives you the next UID.
精彩评论