0

My python code imports imaplib, and goes like:

mail = imaplib.IMAP4_SSL(host=server, port=port)
mail.login(account, password)
mail.select()
typ, msgnums = self.mail.search(*WHERE I WANT TO IMPLEMENT*)

I connect to the server and check the inbox regularly, and save the last seen mail's time data.

For the next mail check, I want to search the mails that have been received since that time, so that I don't have to handle already-seen mails.

I tried to use one of the SEARCH criteria, but it seems that they only care about a date, not a time.

How can I search emails that have been received since a certain time?

yoon
  • 1,177
  • 2
  • 15
  • 28
  • You should search using UIDs. On a correctly implemented server, they always increase, so you can just remember the last UID you successfully fetched, and get any UID larger than that. It’s that simple! – Max Apr 29 '20 at 14:53
  • @Max I considered fetching with UIDs, but isn't a UID changed when some delete operations are done in the mailbox? I did an experiment, and found out that a certain mail's UID is changed after deleting a former email, which I think using UID can not guarantee the accuracy. – yoon May 01 '20 at 05:58
  • 1
    `UID`s don't change from other message being deleted, `MSN`s do (eg, UID SEARCH vs SEARCH and UID FETCH vs FETCH). They are not the same! Unless your server is horridly broken, or you are moving messages between folders, UIDs are stable. – Max May 01 '20 at 14:10

1 Answers1

0

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:

# get emails that have been received since a certain time
import datetime
from imap_tools import MailBox, A
with MailBox('imap.mail.com').login('test@mail.com', 'password', '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

Community
  • 1
  • 1
Vladimir
  • 6,162
  • 2
  • 32
  • 36