Jessica Brown
Jessica Brown

Reputation: 8322

Check for changes/new messages in IMAP4?

I essentially want to do the equivalent of what was asked in this question: How to retrieve only new emails using POP3 protocol but for IMAP4 instead of POP3, so same premise but completely different answer.

If I've already downloaded all the message headers and UIDs and so forth previously and have that information at my disposal, how can I efficiently find out what messages are new/changed/deleted so I can download just those messages without re-downloading all the seen messages?

Currently I'm FETCHing the UID's for each local message ID and seeing if any UID's are new or missing, and then FETCHing the RFC822 data for each new UID. But in practice, this seems terribly slow, so I'd like to see if I can find a more efficient way to identify new/changed messages.

Sent 5/7/2014 9:42:08 AM: C5 FETCH 1 (UID)<EOL>
Recv 5/7/2014 9:42:08 AM: * 1 FETCH (UID 46987)<EOL>C5 OK Fetch completed.<EOL>
Sent 5/7/2014 9:42:08 AM: C6 FETCH 2 (UID)<EOL>
Recv 5/7/2014 9:42:08 AM: * 2 FETCH (UID 46989)<EOL>C6 OK Fetch completed.<EOL>

I've been looking at the [RFC for IMAP][1] and there look like there might be some commands that sound possibly relevant (RECENT for example), but I'm not familiar enough with the ins and outs of IMAP to be sure I'm on the right track with this. [1]: https://www.rfc-editor.org/rfc/rfc3501#section-7.2.4

Upvotes: 0

Views: 473

Answers (1)

bishop
bishop

Reputation: 39494

Use FETCH with a range of [$lastSeenHighestUID+1]:*, per this comment in RFC 3501:

Note: The next unique identifier value is intended to provide a means for a client to determine whether any messages have been delivered to the mailbox since the previous time it checked this value. It is not intended to provide any guarantee that any message will have this unique identifier. A client can only assume, at the time that it obtains the next unique identifier value, that messages arriving after that time will have a UID greater than or equal to that value.

So if the highest UID you saw last was 242, then you would fetch 243:*.

RECENT is not terribly reliable, because the first client will see the flag then remove the flag. If your code is the unlucky second (or nth >= 2), then you'll never know the message was recent.

Upvotes: 1

Related Questions