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

How to detect and correct the Content-Type charset in email header in python?

以编程方式检测和更正 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 中保留电子邮件 body 和 header 的其他部分的正确方法是什么?

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

使用 get_charset 您可以获得消息的 pre-existing 字符集。这是一个示例:

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

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