Python imaplib 搜索包含日期和时间的电子邮件

Ano*_*oop 7 python imaplib python-2.7 python-3.x

我正在尝试阅读特定日期和时间的所有电子邮件。

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')
Run Code Online (Sandbox Code Playgroud)

无需时间即可正常工作。是否也可以用时间来搜索?

Red*_*Red 5

您无法按日期或时间搜索,但是您可以检索指定数量的电子邮件并按日期/时间过滤它们。

import imaplib
import email
from email.header import decode_header

# account credentials
username = "youremailaddress@provider.com"
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)
Run Code Online (Sandbox Code Playgroud)

此示例将为您提供收件箱中最后 3 封电子邮件的日期和时间。N如果您在指定的提取时间内收到超过 3 封电子邮件,您可以调整提取的电子邮件数量。

该代码片段最初由 Abdou Rockikz 在thepythoncode上编写,后来我自己修改以满足您的要求。

抱歉,我迟到了两年,但我也有同样的问题。


Max*_*Max 4

不幸的是没有。RFC 3501 \xc2\xa76.4.4中定义的通用 IMAP 搜索语言不包括任何按时间搜索的规定。

\n

SINCE被定义为采用一个<date>项目,该项目又被定义为date-day "-" date-month "-" date-year,带或不带引号。

\n

IMAP 甚至无法识别时区,因此您必须根据项目在本地过滤掉不适合您的范围的前几条消息INTERNALDATE。您甚至可能需要额外获取几天的消息。

\n

如果您使用的是 Gmail,则可以使用作为扩展程序提供的 Gmail 搜索语言。

\n