在 python 中将 email.HeaderParser 与 imaplib.fetch 一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/703185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:41:44  来源:igfitidea点击:

Using email.HeaderParser with imaplib.fetch in python?

pythonemail

提问by Hortitude

Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch?

有没有人有在 Python 中使用 HeaderParser 类来处理使用 imaplib.fetch 下拉的消息的好例子?

I have been able to find a lot of related things, but nothing that does just this.

我已经能够找到很多相关的东西,但没有什么能做到这一点。

Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects.

我是否需要完全关闭 fetch 具有 RFC822 的内容?我希望简单地拉下主题。

Thanks!

谢谢!

回答by Jarret Hardie

Good news: you're right... you don't need to pull down the RFC822. The message_partsparameter to fetch()lets you be quite fine-grained.

好消息:你是对的……你不需要拉下 RFC822。该message_parts参数fetch()可以让你非常细粒度。

Here's a simple example of how to fetch just the header:

这是一个简单的示例,说明如何仅获取标头:

import imaplib
from email.parser import HeaderParser

conn = imaplib.IMAP4('my.host.com')
conn.login('[email protected]', 'mypassword')
conn.select()
conn.search(None, 'ALL') # returns a nice list of messages...
                         # let's say I pick #1 from this

data = conn.fetch(1, '(BODY[HEADER])')

# gloss over data structure of return... I assume you know these
# gives something like:
# ('OK', [(1 (BODY[HEADER] {1662', 'Received: etc....')])
header_data = data[1][0][1]

parser = HeaderParser()
msg = parser.parsestr(header_data)
<email.message.Message instance at 0x2a>

print msg.keys()
['Received', 'Received', 'Received', 'Cc', 'Message-Id', 'From', 'To',
'In-Reply-To', 'Content-Type', 'Content-Transfer-Encoding', 'Mime-Version',
'Subject', 'Date', 'References', 'X-Mailer', 
'X-yoursite-MailScanner-Information',
'X-yoursite-MailScanner', 'X-yoursite-MailScanner-From', 'Return-Path',
'X-OriginalArrivalTime']

The full list of message parts that can be passed as the second argument to fetchis in the IMAP4 spec: http://tools.ietf.org/html/rfc1730#section-6.4.5

可以作为第二个参数传递的消息部分的完整列表fetch在 IMAP4 规范中:http: //tools.ietf.org/html/rfc1730#section-6.4.5