imaplib: search by uid

some useful imaplib pieces of code that may come in handy to manage your email. my specific use case is that i'm transfering all inbound and outbound email from one of our business shared mailboxes to a pgsql database, so we can easily query any relevant data we want and automate some actions based on specific events (for example, to know when was the last email we spoke to a specific customer (either they contacted us or we send them an email), remove contacts that have bounced emails etc etc.)

result, data = mail.uid('search', None, 'UID ' + str(start_message_uid) + ':*')

if you want to combine multiple conditions:

result, numbers = mail.uid('search', None, '(SINCE "' + date_start + '" BEFORE "' + date_end + '") UID ' + str(last_email_id) + ':*')

date_start, date_end, last_email_id have obviously been defined by me, according to my specific application requirements.


Leave a Reply

Your email address will not be published. Required fields are marked *