Python的 `email.message.as_string`将某些部分编码为base64;不清楚为什么

标签 python email character-encoding base64 mime

我希望使用 Python 的 email 模块将 MIME 邮件消息部分的编码从 quoted-printablebase64 更改为 7 位8 位。一切似乎都很顺利,除了最后,对于某些消息,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)

最佳答案

改用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

关于Python的 `email.message.as_string`将某些部分编码为base64;不清楚为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27095403/

相关文章:

mysql - 在 MySQL 中使用英语、阿拉伯语和中文

mysql - 在基于 Spring MVC 的应用程序中的 mySQL 数据库中存储和检索日语字符

python - 将 QAbstractListModel 声明为 Pyside2 中的属性

sql-server - 从 Excel 电子邮件附件更新 SQL Server (2014) 表

android - 如何从 Android 应用程序通过 Activesync 发送邮件?

email - Office 365 Rest API - 检索纯文本电子邮件

android - 不同的编码问题

Python:如何定义可由多处理池从命令行参数访问的全局变量?

javascript - 如何在 django 1.6.5 中执行 JavaScript

python - 计算来自另一个类的每个 sale.order 上的所有商品 - Odoo v8