我尝试从文件中读取电子邮件,如下所示:
import email
with open("xxx.eml") as f:
msg = email.message_from_file(f)
我得到这个错误:
Traceback (most recent call last):
File "I:\fakt\real\maildecode.py", line 53, in <module>
main()
File "I:\fakt\real\maildecode.py", line 50, in main
decode_file(infile, outfile)
File "I:\fakt\real\maildecode.py", line 30, in decode_file
msg = email.message_from_file(f) #, policy=mypol
File "C:\Python33\lib\email\__init__.py", line 56, in message_from_file
return Parser(*args, **kws).parse(fp)
File "C:\Python33\lib\email\parser.py", line 55, in parse
data = fp.read(8192)
File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 1920: character maps to <undefined>
该文件包含一个多部分电子邮件,其中该部分以 UTF-8 编码。文件的内容或编码可能已损坏,但无论如何我都必须处理它。
我如何读取文件,即使它有 Unicode 错误?我找不到策略对象compat32
,似乎没有办法处理异常并让 Python 在异常发生的地方继续。
我能做些什么?