这是我到目前为止的代码:
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
Run Code Online (Sandbox Code Playgroud)
我目前收到的电子邮件有一堆奇怪的格式.我希望收到电子邮件正文作为纯文本字符串.
在 Python 3.x 中,您可以通过导入“imaplib”和“email”包以非常简单的方式完成此操作。虽然这是一篇较旧的文章,但也许我的回答可以帮助这篇文章的新人。
status, data = self.imap.fetch(num, '(RFC822)')
email_msg = email.message_from_bytes(data[0][1]) #email.message_from_string(data[0][1])
#If message is multi part we only want the text version of the body, this walks the message and gets the body.
if email_msg.is_multipart():
for part in email_msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True) #to control automatic email-style MIME decoding (e.g., Base64, uuencode, quoted-printable)
body = body.decode()
elif part.get_content_type() == "text/html":
continue
Run Code Online (Sandbox Code Playgroud)
现在您可以打印 body 变量,它将采用纯文本格式:) 如果它对您来说足够好,那么选择它作为接受的答案会很好。
(我刚刚使用我的Gmail帐户尝试过此操作.)问题不在于HTML邮件,而是您的邮件是MIME多部分,并且您正在打印完整的字符串.这是因为电子邮件基本上是一种纯文本格式(如上所述); 当人们想要在电子邮件中发送丰富的内容时,他们提出了MIME,这是一种在不修改电子邮件标准的情况下执行此操作的方法.当您print mail,您正在打印完整的MIME邮件,编码,以便它可以作为电子邮件发送.您想要提取有效负载.
但是 - 你已经完成了所有艰苦的工作!只需获取已解析email.message.Message实例的有效负载:
mail.get_payload()[ 0 ].get_payload()
Run Code Online (Sandbox Code Playgroud)
(注意:我必须为我的Gmail收件箱中的第一条消息执行此操作两次,因为它被编码为MIMMultipart,但只有一个叶子.YMMV.)
Getting the right html/text isn't that easy and straightforward. As email can have html as attachment or even multiple HTML. Python 3 gives you a simple method to do that
mail = email.message_from_string(email_body, policy=policy.default)
mail.get_body().get_payload(decode=True)
Run Code Online (Sandbox Code Playgroud)