如何接收html电子邮件作为常规文本? [英] How do I recieve a html email as a regular text?

查看:161
本文介绍了如何接收html电子邮件作为常规文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止的代码:

Here is the code I have thus far:

import email, imaplib

user = 'some username'
pwd = 'some password'

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user, pwd)

m.select("[Gmail]/All Mail")

resp, data = m.fetch(1, "(RFC822)")

email_body = data[0][1]

mail = email.message_from_string(email_body)

print mail

我目前收到一封奇怪格式的电子邮件。我想以纯文本字符串的形式收到电子邮件正文。

I currently receive the email with a bunch of weird formatting. I would like to receive the email body as a plain text string.

推荐答案

(我刚刚用Gmail帐号尝试过)。问题不在于HTML邮件,消息是MIME多部分,您正在打印完整的字符串。这是因为电子邮件基本上是一种纯文本格式(如上所述);当人们想通过电子邮件发送丰富的内容时,他们提出了MIME,这是一种不修改电子邮件标准的方法。当您打印邮件时,您正在打印完整的MIME消息,进行编码,以便可以作为电子邮件发送。你想提取有效载荷。

(I've just tried this with my Gmail account.) The problem isn't the HTML mail, it's that your messages are MIME multipart and you're printing the full string of this. This is because email is fundamentally a plain-text format (as was mentioned above); when people wanted to send rich content in emails they came up with MIME, which is a method to do this without modifying the email standard. When you print mail, you are printing the full MIME message, encoded so that it can be sent as an email. You want to extract the payload.

但是 - 你已经完成了所有的努力!只需得到解析的有效内容 email.message.Message instance:

But -- you've already done all the hard work! Just get the payload of the parsed email.message.Message instance:

mail.get_payload()[ 0 ].get_payload()

(注:我必须这样做我的Gmail收件箱中的第一条消息是两次,因为它被编码为MIMEMultipart,只有一个叶。YMMV。)

(Note: I had to do this twice for the first message in my Gmail inbox because it was encoded as a MIMEMultipart, but with only one leaf. YMMV.)

这篇关于如何接收html电子邮件作为常规文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆