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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With