Python imaplib 搜索带有日期和时间的电子邮件



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

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')

没有时间,它工作正常。也可以随时间搜索吗?

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

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)

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

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

对不起,我迟到了 2 年,但我有同样的问题。

不幸的是不是。 RFC 3501 §6.4.4 中定义的通用 IMAP 搜索语言不包括任何按时间搜索的规定。

SINCE被定义为接受一个<date>项,而项又被定义为date-day "-" date-month "-" date-year,带或不带引号。

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

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

相关内容

最新更新