Search code examples
pythonemailimap

How can I search emails until I encounter a certain email that has a specific field?


My code monitors an email inbox periodically.

The code sample:

mail = imaplib.IMAP4_SSL(host=server, port=port)
mail.login(account, password)
mail.select()
typ, msgnums = self.mail.search(*WHERE I WANT TO IMPLEMENT*)

After one monitoring ends, I save the last seen email's 'Message-ID' field.

For the next monitoring, I want to search the inbox from the latest email to the email that has the 'Message-ID' field.

How can I make this happen?

I've checked imap search criteria, and couldn't find any that can be used for this case.

Thanks :)


Solution

  • After one monitoring ends, I save the last seen email's 'Message-ID' field.

    For the next monitoring, I want to search the inbox from the latest email to the email that has the 'Message-ID' field.

    You can't do that on the Message-ID field because not all smtp providers use dates or increasing serial numbers in the message id. So Message-ID: XYZ can be before or after Message-ID: ABC. See Message-ID vs UID, on SO.

    1. UID works, if used carefully:

    The combination of mailbox name, UIDVALIDITY, and UID must refer to a single immutable message on that server forever.

    Using the example from another SO answer:

        mail.search('UID 2000:*')
    
    1. You could also use the Date fields of the last email checked. Referring to one more SO answer and the SEARCH section of RFC3501:

       typ, msgnums = mail.search('SINCE 1-Feb-1994')
      

    Make sure dates are in that format. You may have an overlap of messages returned within the same 24 hour period, so you'll need to save UIDs also, to avoid re-fetching those.

    1. If your client is the only one accessing the inbox, you could also use UNSEEN but I don't recommend it:

       mail.search('UNSEEN')