Python在Windows中发送带有ZIP附件的邮件失败

0 投票
1 回答
1816 浏览
提问于 2025-04-18 06:29

我正在写一些代码,这段代码会把一个压缩文件(zip文件)写入文件系统,然后将这个压缩文件作为附件发送到电子邮件中。用来创建邮件和附加文件的代码是:

msg = MIMEMultipart()
..
with open( filepath, 'r') as fin:
    data = fin.read()

    part = MIMEBase( 'application', 'octet-stream' )
    part.set_payload( data )
    Encoders.encode_base64( part )

    part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % filename )
    msg.attach( part )
s = smtplib.SMTP( 'mailhost' )                           
s.sendmail( fromAddress, (toAddress,), msg.as_string() ) 
s.close()                                                

在Linux系统下,一切都正常,我可以打开这个附件。

但在Windows系统下,压缩文件正确写入文件系统,我可以打开它,但是尝试在邮件中打开这个压缩附件时却出现了损坏的错误信息。

把一个csv文件(而不是zip文件)附加到邮件中,在Linux和Windows上都能正常工作。

在Linux中解压这个附件时得到:

Archive:  fielname.zip
error [fielname.zip]:  missing 8 bytes in zipfile
  (attempting to process anyway)
retry - request = 0x18446744073709551608
error [fielname.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)
 extracting: filenmae.csv   bad CRC 644faeb2  (should be b19cae37)

Windows上的Python版本是:2.6.6 (r266:84297, 2010年8月24日, 18:46:32) [MSC v.1500 32位 (Intel)]

而在Linux上的版本是:2.6.5 (r265:79063, 2010年3月26日, 10:45:18) \n[GCC 4.4.3]

我觉得可能是编码方面出了问题,但不太确定该从哪里开始查找。

1 个回答

1

在Windows系统中,文件可以用文本模式或二进制模式打开。在文本模式下,系统会自动转换不同类型的换行符(比如将\r\n转换成\n,或者反过来)。这种转换会破坏二进制文件,所以如果你要打开二进制文件,最好用二进制模式来打开。

这一行:

with open( filepath, 'r') as fin:

需要改成:

with open( filepath, 'rb') as fin:

撰写回答