imaplib/gmail如何在不标记读取的同时下载完整的消息(所有部分)

nom*_*cME 5 python gmail imaplib

我无意中将此收件箱中的所有邮件标记为使用此python语句读取:

status, data = conn.uid('fetch', fetch_uids, '(RFC822)')
Run Code Online (Sandbox Code Playgroud)

但我能够通过以下一组陈述来浏览消息的所有部分:

email_message = email.message_from_string(data[0][1])
for part in email_message.walk():
  print '\n'
  print 'Content-Type:',part.get_content_type()
  print 'Main Content:',part.get_content_maintype()
  print 'Sub Content:',part.get_content_subtype()
Run Code Online (Sandbox Code Playgroud)

输出:

Content-Type: multipart/mixed
Main Content: multipart
Sub Content: mixed


Content-Type: multipart/alternative
Main Content: multipart
Sub Content: alternative


Content-Type: text/plain
Main Content: text
Sub Content: plain


Content-Type: text/html
Main Content: text
Sub Content: html
Run Code Online (Sandbox Code Playgroud)

我发现如果我使用这个陈述:

status, data = conn.uid('fetch', fetch_uids, '(RFC822.HEADER BODY.PEEK[1])')
Run Code Online (Sandbox Code Playgroud)

我不会将所有消息都标记为已读.但是,我也不会得到消息的所有部分:

Content-Type: multipart/mixed
Main Content: multipart
Sub Content: mixed
Run Code Online (Sandbox Code Playgroud)

我试着在这里阅读imaplib的手册,但没有提到"peek"这个词.我的问题是,如何在不将我的消息标记为已读的情况下获取消息的所有部分?谢谢.

nom*_*cME 1

如果您只想要标头,但仍希望将消息标记为未读(UNSEEN),则需要两个命令获取然后存储:

# get uids of unseen messages
result, uids = conn.uid('search', None, '(UNSEEN)')

# convert these uids to a comma separated list
fetch_ids = ','.join(uids[0].split())

# first fetch the headers, this will mark them read (SEEN)
status, headers = conn.uid('fetch', fetch_ids, '(RFC822.HEADER)')

# now mark each message unread (UNSEEN)
status1, flags = conn.uid('store', fetch_ids,'-FLAGS','\\Seen')
Run Code Online (Sandbox Code Playgroud)