gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:15 26 4
gpt4 key购买 nike

以编程方式检测和纠正 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com