[英]How to detect and correct the Content-Type charset in email header in python?
What is the correct way to programatically detect and correct the Content-Type
charset
in an email header in python?在 python 中以编程方式检测和更正电子邮件标头中的
Content-Type
charset
的正确方法是什么?
I have a 1000s of emails extracted to .eml
(basically plain text) files and some are encoded shift_jis
, but the charset in the email header doesn't mention this, so they don't display correctly in any email program.我有 1000 封电子邮件被提取到
.eml
(基本上是纯文本)文件,有些是经过编码的shift_jis
,但是电子邮件标题中的字符集没有提到这一点,因此它们无法在任何电子邮件程序中正确显示。 Adding in the charset
manually to the Content-Type
header corrects this.将
charset
手动添加到Content-Type
标头可纠正此问题。
Was:曾是:
Content-Type: text/plain; format=flowed
Needs to be:需要是:
Content-Type: text/plain; charset="shift_jis"; format=flowed
What's the correct way to do this in python preserving the email body and other parts of the header?在python中保留电子邮件正文和标题的其他部分的正确方法是什么?
Also, is there a way to detect which encoding, and only correct those with that encoding?另外,有没有办法检测哪种编码,并且只纠正那些具有该编码的编码? I can't just convert all blindly, since some are
iso_2022_jp
, and those are already displaying correctly.我不能盲目地全部转换,因为有些是
iso_2022_jp
,而那些已经正确显示。
With get_charset you can get the pre-existing charset of a message.使用get_charset,您可以获得消息的预先存在的字符集。 Here's a sample:
这是一个示例:
from email import message_from_file
msg = message_from_file(open('path.eml'))
msg.get_charsets()
[None, 'gb2312', None]
With this approach you can loop through all messages, and using set_charset() set it to the ones that don't have it to the correct one.使用这种方法,您可以遍历所有消息,并使用 set_charset() 将其设置为没有它的那些为正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.