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

标签 python python-3.x python-2.7 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 年,但我有同样的问题。

关于Python imaplib 搜索带有日期和时间的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054196/

相关文章:

Python 相当于 Ruby 'is_a?'

python - 无法安装 rpi_ws281x "error: command ' gcc' 失败,退出状态为 1"

python - 如何清除缓存的查询?

python - 使用 nosetests 的测试超时

python - 替换 bing 搜索的 url 中的变量

python : Get value from a list of Json dictionary

python - 全局名称 '...' 未定义

python - 对时间进行四舍五入和四舍五入

python - Tkinter 时钟因无限循环而崩溃?

python - 如果,elif,否则故障?