imap

Fetching New Mail in IMAP using UID and MODSEQ


I'm writing a small email parsing program using IMAP. When I first connect to my mail server I get UIDNEXT and HIGHESTMODSEQ, then go into IDLE and wait for new changes. After I get an Idle message I do a search and fetch all messages with a higher MODSEQ than MODSEQHIGHEST and UID greater than or equal to UIDNEXT. My question is how do I update these values after my fetches. Do I need to query the server for UIDNEXT and HIGHESTMODSEQ again? I know search returns the highest MODSEQ of the messages from my serch and I can get the highest UID of my messages returned by search, but is UIDNEXT always just my current highest UID+1?

I tried just fetching messages with MODSEQ greater than the MODSEQ value returned by my search but this results in me seeing messages I've already processed in subsequent searches.


Solution

  • UIDNEXT doesn't strictly have be one larger than the largest UID you've seen, but searching for the uid+1 necessarily produces the same results.

    Suppose you've fetched UID 1000 and want the next larger. If the server skips 1001, searching for 1001:* and 1002:* must produce the same result, see?

    It sounds as if you can skip MODSEQ in your case. MODSEQ is incremented when someone e.g. sets/clears the seen flag on a message. If you want to keep a cache updated the up-to-date seenness, you need to use MODSEQ. In your case it sounds as if you just want to process new messages: UID is all you need.