python - 如何在 python 中检测并更正电子邮件 header 中的 Content-Type 字符集?

标签 python email character-encoding shift-jis

以编程方式检测和纠正 python 中电子邮件 header 中的 Content-Type charset 的正确方法是什么?

我有 1000 封电子邮件提取到 .eml(基本上是纯文本)文件,其中一些经过编码 shift_jis,但电子邮件 header 中的字符集没有提及这样,它们就无法在任何电子邮件程序中正确显示。手动将 charset 添加到 Content-Type header 可以纠正此问题。

曾经:

Content-Type: text/plain; format=flowed

需要:

Content-Type: text/plain; charset="shift_jis"; format=flowed

在 python 中保留电子邮件正文和标题的其他部分的正确方法是什么?

另外,有没有办法检测哪种编码,并只纠正那些具有该编码的编码?我不能盲目地全部转换,因为有些是 iso_2022_jp,而且它们已经正确显示。

最佳答案

get_charset您可以获得消息预先存在的字符集。这是一个示例:

from email import message_from_file
msg = message_from_file(open('path.eml'))
msg.get_charsets()
[None, 'gb2312', None]

通过这种方法,您可以循环遍历所有消息,并使用 set_charset() 将其设置为没有正确消息的消息。

关于python - 如何在 python 中检测并更正电子邮件 header 中的 Content-Type 字符集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677046/

相关文章:

python - 打印排序列表

JavaScript - 如何转换 unicode 字符?英语数字到波斯语数字

python - matplotlib 连接散点图中的点

python - 静态文件 application_readable 用法

python - Docker pip3未安装软件包

php - HORDE Imap PHP 客户端 - 如何获取消息

java - Freemarker 在 ftl 上嵌入图像

email - 如何使用groovy模板在Jenkins中发送电子邮件?

javascript - 如何在 JavaScript 中使用 ISO-8859-15 字符集生成字符串?

php - 从mysql表中读取数据时出现奇怪的字符