[英]Fetching multiple IMAP messages at once
The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. 我见过的关于使用python通过IMAP加载电子邮件的示例进行搜索,然后对结果中的每个消息ID进行查询。 I want to speed things up by fetching them all at once.
我想通过一次取出它们来加快速度。
RFC 3501 says fetch takes a sequence set, but I didn't see a definition for that and the example uses a range form (2:4 = messages 2, 3, and 4). RFC 3501说fetch需要一个序列集,但我没有看到它的定义,该示例使用范围形式(2:4 =消息2,3和4)。 I figured out that a comma separated list of ids works.
我发现逗号分隔的ID列表有效。 In python with imaplib, I've got something like:
在使用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
You can try this to fetch the header information of all the mails in just 1 Go to server. 您可以尝试此操作来获取所有邮件的标题信息,只需1转到服务器。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.