我希望使用 Python 的 email
模块将 MIME 邮件消息部分的编码从 quoted-printable
或 base64
更改为 7 位
或8 位
。一切似乎都很顺利,除了最后,对于某些消息,email.message.as_string
对某些部分进行编码(text/plain
和 text/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/