Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python imaplib search email with date and time

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?

like image 218
Anoop Avatar asked Aug 28 '18 09:08

Anoop


2 Answers

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 ID
    res, msg = imap.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = 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.

like image 106
Red Avatar answered Oct 03 '22 22:10

Red


Unfortunately not. The generic IMAP search language as defined in RFC 3501 §6.4.4 does not include any provision for searching by time.

SINCE is defined to take a <date> item, which is in turn defined as date-day "-" date-month "-" date-year, either with or without quotation marks.

IMAP is not even time zone aware, so you will have to locally filter out the first few messages that don't fit in your range based on their INTERNALDATE item. You may even have to fetch an extra days worth of messages.

If you're using Gmail, you may be able to use the Gmail search language which is available as an extension.

like image 39
Max Avatar answered Oct 03 '22 22:10

Max