Skip to content
Advertisement

Search Email Of Last N Minutes Using IMAP-TOOLS

The following code uses IMAP to log into an Outlook email and checks the contents of the Junk folder.

It returns the content of the last unseen email with subject "Title".

I would like to add one thing to the source code.

Is it possible to get the last email of for example the last 10 minutes? So that he doesn’t return older emails.

from imap_tools import MailBox, AND

with MailBox('imap.outlook.com').login(email, password, 'Junk') as mailbox:
    for msg in mailbox.fetch(AND(subject = f'title', seen = False), limit = 1, reverse = True):
        body = msg.text
    for line in body.splitlines():
        print(line)

Advertisement

Answer

There is no search by time in IMAP REF: https://www.rfc-editor.org/rfc/rfc3501#section-6.4.4

Anyway you can do it:

import datetime
from imap_tools import MailBox, A

# get emails that have been received since a certain time
with MailBox('imap.mail.com').login('test@mail.com', 'p', 'INBOX') as mailbox:
    for msg in mailbox.fetch(A(date_gte=datetime.date(2000, 1, 1))):
        print(msg.date.time(), 'ok' if msg.date.hour > 8 else '')
    

https://github.com/ikvk/imap_tools , I am author

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement