我經常收到帶有必須解壓縮並保存到磁盤的附件的電子郵件。我基本上做以下(在Python 2.7):壓縮的附件中斷email.message.Message.get_payload()
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)
這種方法已經爲所有類型的附件和我到目前爲止已經收到除非該附件是一個ZIP文件和Content-Transfer-Encoding
的Content-Transfer-Encoding所有口味是'引用 - 可打印的'。在這種情況下是被寫入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文件,它處理連接爲「引用可打印」就好了其他內容(Excel文件,CSV文件)。我知道ZIP附件的內容是無損的足夠,我的普通電子郵件閱讀器可以將其保存到磁盤就好,並提取完美的原始內容。 (真的電子郵件閱讀器在保存我的Python沒有做的附件時可能會執行一些錯誤更正嗎?)
是否有一個已知的問題,Python無法讀取以引用打印方式發送的ZIP文件?有沒有其他函數來自Python的email
包我可以嘗試正確解密這個內容?
請勿使用_ ** quoted-printable ** _,請改用'base-64'。 – stovfl
@stovfl謝謝,但我是電子郵件的收件人,而不是發件人。 – dg99
Zip文件是'binary',你不能從** quoted-printable **解碼。要求發件人更改爲'base64'。 – stovfl