I'm trying to read all emails from a particular date and time.
mail = imaplib.IMAP4_SSL(self.url, self.port)
mail.login(user, password)
mail.select(self.folder)
since = datetime.strftime(since, '%d-%b-%Y %H:%M:%S')result, data = mail.uid('search', '(SINCE "'+since+'")', 'UNSEEN')
It is working fine without time. Is it possible to search with time also?
You are not able to search by date or time, however you can retrieve a specified number of emails and filter them by date/time.
import imaplib
import email
from email.header import decode_header# account credentials
username = "[email protected]"
password = "yourpassword"# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)status, messages = imap.select("INBOX")
# number of top emails to fetch
N = 3
# total number of emails
messages = int(messages[0])for i in range(messages, messages-N, -1):# fetch the email message by IDres, msg = imap.fetch(str(i), "(RFC822)")for response in msg:if isinstance(response, tuple):# parse a bytes email into a message objectmsg = email.message_from_bytes(response[1])date = decode_header(msg["Date"])[0][0]print(date)
This example will give you the date and time for the last 3 emails in your inbox. You can adjust the number of emails fetched N
if you get more than 3 emails in your specified fetch time.
This code snippet was originally written by Abdou Rockikz at thepythoncode and later modified by myself to fit your request.
Sorry I was 2 years late but I had the same question.