7

我见过的关于使用 python 通过 IMAP 加载电子邮件的示例进行搜索,然后对结果中的每个消息 ID 进行查询。我想通过一次获取它们来加快速度。

4

2 回答 2

16

RFC 3501 说 fetch 需要一个序列集,但我没有看到它的定义,示例使用范围形式(2:4 = 消息 2、3 和 4)。我发现逗号分隔的 id 列表有效。在带有 imaplib 的 python 中,我有类似的东西:

    status, email_ids = con.search(None, query)
    if status != 'OK':
        raise Exception("Error running imap search for spinvox messages: "
                        "%s" % status)

    fetch_ids = ','.join(email_ids[0].split())
    status, data = con.fetch(fetch_ids, '(RFC822.HEADER BODY.PEEK[1])')
    if status != 'OK':
        raise Exception("Error running imap fetch for spinvox message: "
                        "%s" % status)
    for i in range(len(email_ids[0].split())):
        header_msg = email.message_from_string(data[i * 3 + 0][1])
        subject = header_msg['Subject'],
        date = header_msg['Date'],
        body = data[i * 3 + 1][1] # includes some mime multipart junk
于 2010-08-27T05:57:20.177 回答
3

您可以尝试使用 1 Go to server 来获取所有邮件的标头信息。

import imaplib
import email

obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('folder_name')
resp,data = obj.uid('FETCH', '1:*' , '(RFC822.HEADER)')
messages = [data[i][1].strip() + "\r\nSize:" + data[i][0].split()[4] + "\r\nUID:" + data[i][0].split()[2]  for i in xrange(0, len(data), 2)]
for msg in messages:
    msg_str = email.message_from_string(msg)
    message_id = msg_str.get('Message-ID')
于 2010-09-27T10:00:18.107 回答