IMAP: Search for messages with UID greater than X (or generally, after my last search)

Parand picture Parand · Feb 5, 2012 · Viewed 9k times · Source

I'm writing a script to analyze my mailbox and want to periodically check for new messages. The search criteria would be: give me the UIDs for all emails with UID greater than X, where X is the UID of the last email I processed.

Or, more generally, I'm looking for a way to only see messages since my last search.

Note that I'm not looking for seen/unseen messages; the script opens the mailbox as read-only, and I'd like it to not interfere with my flags, etc.

I know I can specify a date in the IMAP search, but the granularity of that seems to be by day, so not exactly what I need.

I'm starting with Gmail as the IMAP server, but would like to support generic IMAP servers in the future.

Is there way to search for emails with UID greater than X? Or another means of specify all messages since message X?

Answer

SimonMayer picture SimonMayer · Feb 5, 2012

You can use IMAP SEARCH for UIDs. Assuming your most recently fetched UID is 1999, I think you would do:

SEARCH UID 2000:*