Search code examples
imap

Find each folder's starting UID in IMAP efficiently


SELECT, EXAMINE and STATUS command would give me UIDNEXT value of each mailbox(folder). What I am looking for is an efficient way to determine something like UIDFIRST i.e. starting UID for each mailbox. I understand that there is no direct command get it.

I can get all the UIDs for a folder by using UID SEARCH ALL like given here

P.S. The result is not guaranteed to be in ascending order as given in the RFC.

This would result me with all the UIDs available in that particular selected mailbox and I could sort them and get the smallest UID from the list of UIDs.

Consider a mailbox with nearly a million mails in it. It would not be efficient for the network call as well as parsing the result into list of numbers and sorting them.

Is there any other work around which might be efficient to get the first UID of each mailbox?


Solution

  • The command you want is a fetch 1 uid, it'll always return the lowest UID, except if the mailbox is empty. The same effect can be achieved with a uid search 1, ie. search for the message with MSN 1 and return its UID if the mailbox is nonempty or an empty result if the mailbox is empty. Use whichever suits your fancy.

    1 is the lowest because UIDs have to be in ascending order, see 3501 page 9. I don't think the search command is required to return the messages in any particular order, but MSNs and UID absolutely have to ascend together.