使用 python imap 和 email 包获取电子邮件的正文 [英] Get body text of an email using python imap and email package

查看:55
本文介绍了使用 python imap 和 email 包获取电子邮件的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python imap 和电子邮件包检索电子邮件的正文(仅文本).

I want to retrieve body (only text) of emails using python imap and email package.

根据这个SO 线程,我正在使用以下代码:

As per this SO thread, I'm using the following code:

mail = email.message_from_string(email_body)
bodytext = mail.get_payload()[ 0 ].get_payload()

虽然它在某些情况下工作正常,但有时我会得到类似于以下响应

Though it's working fine for some instances, but sometime I get similar to following response

[<email.message.Message instance at 0x0206DCD8>, <email.message.Message instance at 0x0206D508>]

推荐答案

您假设消息具有统一的结构,具有一个明确定义的主要部分".事实并非如此;可以有单个部分的消息,它不是文本部分(只是二进制文件的附件",没有别的),或者它可以是具有多个文本部分的多部分(或者,再一次,根本没有),甚至如果只有一个,则不必是第一部分.此外,还有嵌套的多部分(一个或多个部分是另一个 MIME 消息,递归).

You are assuming that messages have a uniform structure, with one well-defined "main part". That is not the case; there can be messages with a single part which is not a text part (just an "attachment" of a binary file, and nothing else) or it can be a multipart with multiple textual parts (or, again, none at all) and even if there is only one, it need not be the first part. Furthermore, there are nested multiparts (one or more parts is another MIME message, recursively).

总之,您必须检查 MIME 结构,然后决定哪些部分与您的应用程序相关.如果您只接收来自相当静态的一小部分客户端的消息,您可能会走捷径(至少在 Microsoft Plague 的下一次升级到来之前),但总的来说,根本没有任何类型的层次结构,只是一组(不一定总是直接相关的)同样重要的部分.

In so many words, you must inspect the MIME structure, then decide which part(s) are relevant for your application. If you only receive messages from a fairly static, small set of clients, you may be able to cut some corners (at least until the next upgrade of Microsoft Plague hits) but in general, there simply isn't a hierarchy of any kind, just a collection of (not necessarily always directly related) equally important parts.

这篇关于使用 python imap 和 email 包获取电子邮件的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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