【问题标题】:Why I am getting a byte-string even after decoding in python-3 email message parsing?为什么即使在 python-3 电子邮件解析中解码后我也得到一个字节字符串?
【发布时间】:2019-10-03 15:38:33
【问题描述】:

我正在使用 imaplib 提取电子邮件,并且必须从中提取文本。

我的消息是多部分的,所以

typ , data = account.fetch(msg_uid , '(RFC822)')
raw_email = data[0][1]
msg = email.message_from_bytes(raw_email)
payload_msg = get_message(msg)

def get_message(message):
    '''
    This function returns an decoded body text of a message, depending on multipart\* or text\*
    :param message: message content of an email
    :return: body of email message
    '''
    body = None
    if message.is_multipart():
        print(str(message.get_content_type()) + ' is the message content type')
        for part in message.walk():
            cdispo = str(part.get('Content-Disposition'))
            if part.is_multipart():
                for subpart in part.walk():
                    cdispo = str(subpart.get('Content-Disposition'))
                    if subpart.get_content_type() == 'text/plain' and 'attachment' not in cdispo:
                        body = subpart.get_payload(decode=True)
                    elif subpart.get_content_type() == 'text/html':
                        body = subpart.get_payload(decode=True)
            elif part.get_content_type() == 'text/plain' and 'attachment' not in cdispo:
                body = part.get_payload(decode=True)
            elif part.get_content_type() == 'text/html' and 'attachment' not in cdispo:
                body = part.get_payload(decode=True)
    elif message.get_content_type() == 'text/plain':
        body = message.get_payload(decode=True)
    elif message.get_content_type() == 'text/html':
        body = message.get_payload(decode=True)
    return body

现在,如果您看到上面的代码,msg 是我们正在获取并将其传递给 get_payload 方法的内容,其中 decode = True。但是当我获取正文并检查类型时,它仍然以字节为单位!为什么?

难道不是要转成字符串吗,奇怪的是我给decode=False的时候,是字符串格式的!我在这里做错了什么?我预计这里会出现相反的情况!

P.S : raw_email 在这里是字节,而 msg 在这里是一些 email.message 类型!

【问题讨论】:

    标签: python-3.x encoding utf-8 decoding


    【解决方案1】:

    According to the docsdecode 标志不是关于文本编码,而是关于引用打印和 base64 编码。 所以它不应该改变返回值的类型,只改变它的内容。

    此外,文档还提到了 get_payload() 方法:

    这是一种传统方法。在 EmailMessage 类中,它的功能被 get_content()iter_parts() 取代。

    所以你应该考虑改用这些方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多