在Windows上,python发送带有zip附件的邮件失败

在Windows上,python发送带有zip附件的邮件失败,python,email,smtplib,Python,Email,Smtplib,我正在编写一些代码,将一个zip文件写入文件系统,然后将该zip文件作为附件发送到电子邮件中。用于创建邮件和附加文件的代码为: msg = MIMEMultipart() .. with open( filepath, 'r') as fin: data = fin.read() part = MIMEBase( 'application', 'octet-stream' ) part.set_payload( data ) Encoders.encode_ba

我正在编写一些代码,将一个zip文件写入文件系统,然后将该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下,zip文件正确写入文件系统,我可以打开,但是尝试打开电子邮件中的zip附件失败,并显示损坏错误消息

将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位(英特尔)]

linux上的is:2.6.5(r265:790632010年3月26日10:45:18)\n[GCC 4.4.3]


我认为编码有问题,但不确定从哪里开始查找。

在Windows上,文件可以以文本模式或二进制模式打开。在文本模式下,可以在不同类型的行分隔符之间执行自动转换(例如,
\r\n
\n
或反之亦然)。这将损坏二进制文件,因此可以通过在二进制模式下打开二进制文件来避免

这一行:

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

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

啊,就是这样。不知怎的,我错过了这个!