【问题标题】:How do I determine if an email is Base64 encoded?如何确定电子邮件是否经过 Base64 编码?
【发布时间】:2010-09-24 09:50:06
【问题描述】:

我很难确定文本电子邮件的正文是否为 base64 编码。 如果是,则使用这行代码; 使用 jython 2.2.1

dirty=base64.decodebytes(dirty)

否则照常继续。

这是我的自动取款机代码。哪行代码可以让我从电子邮件中提取:

“内容传输编码:base64”

import email, email.Message
import base64

def _get_email_body(self):
    try:
        parts=self._email.get_payload()
        check=parts[0].get_content_type()
        if check=="text/plain":
            part=parts[0].get_payload()
            enc = part[0]['Content-Transfer-Encoding']
            if enc == "base64":
                dirty=base64.decodebytes(dirty)
        elif check=="multipart/alternative":
            part=parts[0].get_payload()
            enc = part[0]['Content-Transfer-Encoding']
            if part[0].get_content_type()=="text/plain":
                dirty=part[0].get_payload()
                if enc == "base64":
                    dirty=base64.decodebytes(dirty)
            else:
                return "cannot obtain the body of the email"
        else:
            return "cannot obtain the body of the email"
        return dirty
    except:
        raise

好的,这段代码现在可以工作了!谢谢大家

【问题讨论】:

标签: python email encoding jython email-headers


【解决方案1】:

它是一个标头,但您必须先从消息中获取有效负载。

会是:

header = msg.get_payload()[0]
header['Content-Transfer-Encoding']

我正在使用 Python 3

【讨论】:

  • 似乎有时它包含在消息对象中,有时它包含在 message.get_payload()[0] 中,正如 Leon 所提到的。有人可以澄清一下吗?
  • 它是消息每个部分的标头。因此主体部分(文本或 html)可以不同,任何附件也可以不同。如上所述,您必须获取每个部分的有效负载,然后确定 Content-Transfer-Encoding。我很惊讶它没有被添加为属性,但是由于我不够聪明,无法编写整个电子邮件类,因此我不会过多批评;-)
【解决方案2】:

试试:

enc = msg['Content-Transfer-Encoding']

它是一个标题,因此您将无法查看正文。您应该能够在找到主题的地方找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2011-12-30
    • 2012-04-24
    • 2011-12-09
    • 2014-11-16
    • 2020-04-29
    • 2021-03-21
    相关资源
    最近更新 更多