问题描述
有没有人有一个很好的例子,在Python中使用HeaderParser类,您可以使用imaplib.fetch下拉一条消息?我已经能够找到很多相关的东西,但没有什么只是这样。
我需要完整的抓取有一个RFC822?我希望简单地拉下主题。
谢谢!
p>好消息:你是对的...你不需要拉下RFC822。 message_parts
参数到 fetch()
可以让你相当细微。
这是一个简单的例子,说明如何仅获取标题:
从电子邮件中导入imaplib
.parser import HeaderParser
conn = imaplib.IMAP4('my.host.com')
conn.login('my@username.com','mypassword')
conn.select()
conn.search(None,'ALL')#返回一个不错的消息列表...
#让我们说从这个
中选择#1 data = conn.fetch(1,'(BODY [HEADER])')
#返回数据结构的光泽...我假设你知道这些
#给出了如下:
#('OK',[(1(BODY [HEADER] {1662','Received:etc ....')])
header_data = data [1] [0] [1]
parser = HeaderParser()
msg = parser.parsestr(header_data)
< email.message.Message实例在0x2a&$
打印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']
可以作为 fetch
的第二个参数传递的消息部分的完整列表位于IMAP4规范中:
Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with 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.
Thanks!
Good news: you're right... you don't need to pull down the RFC822. The message_parts
parameter to fetch()
lets you be quite fine-grained.
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('my@username.com', '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 fetch
is in the IMAP4 spec: http://tools.ietf.org/html/rfc1730#section-6.4.5
这篇关于在python中使用email.HeaderParser和imaplib.fetch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!