Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带日期和时间的Python imaplib搜索电子邮件_Python_Python 3.x_Python 2.7_Imaplib - Fatal编程技术网

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

带日期和时间的Python imaplib搜索电子邮件,python,python-3.x,python-2.7,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'

我试图阅读某个特定日期和时间的所有电子邮件

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

没有时间,它工作得很好。也可以用时间搜索吗?

不幸的是,不能。中定义的通用IMAP搜索语言不包括任何按时间搜索的规定

因为
被定义为接受一个
项,而该项又被定义为
日期-日期-日期-月份-日期-日期-年份
,可以带引号,也可以不带引号

IMAP甚至不支持时区,因此您必须根据其
INTERNALDATE
项在本地筛选出不适合您范围的前几条消息。您甚至可能需要额外获取几天的消息


如果您使用的是Gmail,您可以使用Gmail搜索语言,该语言可以作为一种搜索语言提供。

您不能按日期或时间进行搜索,但是您可以检索指定数量的电子邮件并按日期/时间进行过滤

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在PythonCode上编写,后来由我自己修改以满足您的要求

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