Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter gmail imap messages for date in python?

I have the following code which signs into gmail via imap, selects the inbox, and searches the mailbox for emails that come from [email protected]

How do I filter the data from gmail so that it returns only messages that have a date of today?

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(username, password)
m.select('inbox') 
resp, data = m.search(None, '(FROM "[email protected]")')
return data

I'm using the following module:

https://docs.python.org/2/library/imaplib.html

like image 334
Chris Avatar asked Sep 15 '25 03:09

Chris


2 Answers

imaplib is just a simple wrapper around the IMAP protocol which is described in this RFC, the specific part of this you would want to look at is the SEARCH command.

In answer to your question to select all messages in the current mailbox that arrived e.g. on 19th February 2015 you would perform the query (ON 19-Feb-2015)

Some python code which will format todays date in the correct way to make the query would be:

import time
resp, data = m.search(None, "(ON {0})".format( time.strftime("%d-%b-%Y") ) )

now data will contain a list of message numbers recieved today.

like image 85
Simon Gibbons Avatar answered Sep 16 '25 17:09

Simon Gibbons


You can use SENTSINCE to get most recent messages

date = (datetime.date.today() - datetime.timedelta(days=2)).strftime("%d-%b-%Y")
typ, messages = m.search(None, '(ALL)', f'(SENTSINCE {date})')

To get only today messages you can use

date = datetime.date.today().strftime("%d-%b-%Y")

Une can as well replace '(ALL)' by '(UNSEEN)' to get only unseen messages

like image 43
Rukamakama Avatar answered Sep 16 '25 17:09

Rukamakama