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 :)
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.
UID
works, if used carefully:The combination of mailbox name,
UIDVALIDITY
, andUID
must refer to a single immutable message on that server forever.
Using the example from another SO answer:
mail.search('UID 2000:*')
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.
If your client is the only one accessing the inbox, you could also use UNSEEN
but I don't recommend it:
mail.search('UNSEEN')