我经常收到带有附件的电子邮件,我必须提取这些附件并保存到磁盘。我基本上做了以下事情(在 Python 2.7 中):
message = email.message_from_file(sys.stdin)
for part in message.walk():
path = email.header.decode_header(part.get_filename())[0][0]
content = part.get_payload(decode=True)
with open(path, 'w') as f:
f.write(content)
这种方法适用于我迄今为止收到的所有类型的附件和所有风格的内容传输编码Content-Transfer-Encoding
,除非附件是 ZIP 文件并且是“引用打印”。在这些情况下,被写入的 ZIP 文件比原始文件少一个字节(大约 60-80% 通过文件),并unzip
报告如下错误:
% unzip -l foo.zip
Archive: foo.zip
error [foo.zip]: missing 1 bytes in zipfile
(attempting to process anyway)
Length Date Time Name
--------- ---------- ----- ----
440228 01-00-1980 00:00 foo - bar.csv
--------- -------
440228 1 file
和
% unzip foo.zip
Archive: foo.zip
error [foo.zip]: missing 1 bytes in zipfile
(attempting to process anyway)
error [foo.zip]: attempt to seek before beginning of zipfile
(please check that you have transferred or created the zipfile in the
appropriate BINARY mode and that you have compiled UnZip properly)
(attempting to re-compensate)
inflating: foo - bar.csv bad CRC 4c86de66 (should be a53f73b1)
然后,解压缩的结果与原始 CSV 的大小相差约 0.01%,最后 20-40% 左右的文件出现乱码。
现在,该代码可以很好地处理附加为“base64”的 ZIP 文件,并且可以很好地处理附加为“quoted-printable”的其他内容(Excel 文件、csv 文件)。我知道 ZIP 附件内容足够干净,以至于我的普通电子邮件阅读器可以很好地将其保存到磁盘并完美地提取原始内容。(在保存我的 Python 没有执行的附件时,真正的电子邮件阅读器是否可能会执行一些错误更正?)
Python 是否存在一个已知问题,无法读取作为引用打印发送的 ZIP 文件?Python 包中是否还有其他功能email
可以尝试正确破译这些内容?