Skip to main content
 首页 » 编程设计

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

2024年12月31日32lovecherry

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

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 年,但我有同样的问题。