Python';s`email.message.as_string`将某些部分编码为base64;不清楚为什么
我希望使用Python的Python';s`email.message.as_string`将某些部分编码为base64;不清楚为什么,python,email,character-encoding,base64,mime,Python,Email,Character Encoding,Base64,Mime,我希望使用Python的email模块将MIME邮件消息部分的编码从quoted printable或base64更改为7bit或8bit。所有这些似乎都解决了,除了在最后,对于一些消息,email.message.as___string将一些部分(text/plain和text/html都遇到)编码为base64。我不明白为什么,以及如何理解这种行为来避免它 脚本代码: # Read and parse the message from stdin msg = email.message_fr
email
模块将MIME邮件消息部分的编码从quoted printable
或base64
更改为7bit
或8bit
。所有这些似乎都解决了,除了在最后,对于一些消息,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())
(如果这很重要:我使用Python3.3)使用
作为字节。因此,请将打印更改为:
print(msg.as_bytes().decode(encoding='UTF-8'))
原因在政策文件中
8bit的cte_类型值仅适用于BytesGenerator,而不适用于Generator,因为字符串不能包含二进制数据。如果生成器在指定cte_type=8bit的策略下运行,则其行为将如同cte_type为7bit一样
正如字符串使用生成器,但字节使用BytesGenerator,您需要它如果我尝试这样做,我会得到AttributeError:“Message”对象没有属性“as\u bytes”
@equalhe:它在Python 3.4中是新的;既然您使用的是3.3,那就太不幸了。@equale您仍然可以在3.3中直接使用BytesGenerator。只需使用as_bytes docs中的代码片段(因为这是BytesGenerator中唯一方便的方法)from io import BytesIO from email.generator import BytesGenerator fp=BytesIO()g=BytesGenerator(fp,mangle_from_u=True,maxheaderlen=60)g.flatten(msg)text=fp.getvalue()
3.4可用并与3.3并行安装在我的系统上,所以我可以通过调用python3.4而不是python3来使用它。