【问题标题】:Python's `email.message.as_string` encodes some parts as base64; unclear whyPython 的 `email.message.as_string` 将某些部分编码为 base64;不清楚为什么
【发布时间】:2015-01-21 14:36:03
【问题描述】:

我希望使用 Python 的 email 模块将 MIME 邮件消息部分的编码从 quoted-printablebase64 更改为 7bit8bit。一切似乎都解决了,除了最后,对于某些消息,email.message.as_string 将某些部分(text/plaintext/html 都遇到)编码为base64。我不明白为什么,以及如何理解这种行为来避免它。

脚本代码:

# Read and parse the message from stdin
msg = email.message_from_string(sys.stdin.read())

for part in msg.walk():
  if part.get_content_maintype() == 'text':
    if part['Content-Transfer-Encoding'] in {'quoted-printable', 'base64'}:
      payload = part.get_payload(decode=True)
      del part['Content-Transfer-Encoding']
      part.set_payload(payload)
      email.encoders.encode_7or8bit(part)

# Send the modified message to stdout
print(msg.as_string())

(如果这很重要:我使用 Python 3.3)

【问题讨论】:

    标签: python email character-encoding base64 mime


    【解决方案1】:

    请改用as_bytes。因此,将您的打印更改为:

    print(msg.as_bytes().decode(encoding='UTF-8'))

    原因在政策文档中 https://docs.python.org/3.4/library/email.policy.html#module-email.policy

    8bit 的 cte_type 值仅适用于 BytesGenerator,不适用于 Generator,因为字符串不能包含二进制数据。如果生成器在指定 cte_type=8bit 的策略下运行,则它的行为就像 cte_type 为 7bit。

    而 as_string 使用 Generator,但是 as_bytes 使用你需要的 BytesGenerator

    【讨论】:

    • 如果我尝试这样做,我会得到AttributeError: 'Message' object has no attribute 'as_bytes'
    • @equaeghe:它是 Python 3.4 中的新功能;因为你使用的是 3.3,这很不幸。
    • @equaeghe 你仍然可以在 3.3 中直接使用 BytesGenerator。只需使用 as_bytes 文档中的 sn-p (因为它只是 BytesGenerator 周围的方便方法)from io import BytesIO from email.generator import BytesGenerator fp = BytesIO() g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60) g.flatten(msg) text = fp.getvalue()
    • 3.4 可用并与 3.3 并行安装在我的系统上,因此我可以通过调用 python3.4 而不是 python3 来使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2019-05-05
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多