1

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)
Vladimir
  • 6,162
  • 2
  • 32
  • 36
  • Does this answer your question? [Python imaplib search email with date and time](https://stackoverflow.com/questions/52054196/python-imaplib-search-email-with-date-and-time) – Vladimir Feb 25 '22 at 03:57
  • You can however remember the UID of the last message you processed, and only search for messages newer than that. The raw search term would be 'UID SEARCH UID n:*' where n is the last message you saw. Note this will return the last message you saw as well, so you can filter it out. – Max Feb 26 '22 at 17:28

1 Answers1

2

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

Vladimir
  • 6,162
  • 2
  • 32
  • 36