python接收邮件内容启动程序,如何使用python获取电子邮件的文本内容?

Given an RFC822 message in Python 2.6, how can I get the right text/plain content part? Basically, the algorithm I want is this:

message = email.message_from_string(raw_message)

if has_mime_part(message, "text/plain"):

mime_part = get_mime_part(message, "text/plain")

text_content = decode_mime_part(mime_part)

elif has_mime_part(message, "text/html"):

mime_part = get_mime_part(message, "text/html")

html = decode_mime_part(mime_part)

text_content = render_html_to_plaintext(html)

else:

# fallback

text_content = str(message)

return text_content

Of these things, I have get_mime_part and has_mime_part down pat, but I'm not quite sure how to get the decoded text from the MIME part. I can get the encoded text using get_payload(), but if I try to use the decode parameter of the get_payload() method (see the doc) I get an error when I call it on the text/plain part:

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email/message.py", line 189, in get_payload

raise TypeError('Expected list, got %s' % type(self._payload))

TypeError: Expected list, got

In addition, I don't know how to take HTML and render it to text as closely as possible.

解决方案

In a multipart e-mail, email.message.Message.get_payload() returns a list with one item for each part. The easiest way is to walk the message and get the payload on each part:

import email

msg = email.message_from_string(raw_message)

for part in msg.walk():

# each part is a either non-multipart, or another multipart message

# that contains further parts... Message is organized like a tree

if part.get_content_type() == 'text/plain':

print part.get_payload() # prints the raw text

For a non-multipart message, no need to do all the walking. You can go straight to get_payload(), regardless of content_type.

msg = email.message_from_string(raw_message)

msg.get_payload()

If the content is encoded, you need to pass None as the first parameter to get_payload(), followed by True (the decode flag is the second parameter). For example, suppose that my e-mail contains an MS Word document attachment:

msg = email.message_from_string(raw_message)

for part in msg.walk():

if part.get_content_type() == 'application/msword':

name = part.get_param('name') or 'MyDoc.doc'

f = open(name, 'wb')

f.write(part.get_payload(None, True)) # You need None as the first param

# because part.is_multipart()

# is False

f.close()

As for getting a reasonable plain-text approximation of an HTML part, I've found that html2text works pretty darn well.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值