使用 smtplib 进行发送邮件MIMEApplication进行附件封装,Outlook下无法收到邮件附件?


问题如题

发送邮箱:


 使用163.com qq.com. sina.cn 都出现相同问题
其他客户端,网页端均正常,求解!
代码如下

msg = MIMEMultipart('alternative')
text_mail = MIMEText(content,content_type,'utf-8')
from_add = "[email protected]"
from_pwd = "1000000"
smtp_server = "smtp.qq.com"

msg['From'] = _format_addr('某某 <%s>' % from_add)
msg['To'] = _format_addr('%s <%s>' % (to_name,to_add))
msg['Subject'] =  Header('%s'% subject,'utf-8').encode()
msg.attach(text_mail)

file_mail = MIMEApplication(open(fileurl,'rb').read())  
file_mail.add_header('Content-Disposition', 'attachment', filename=filename.decode('utf-8').encode('gb2312'))  
msg.attach(file_mail)
server = smtplib.SMTP(smtp_server, 587)
server.starttls()
server.set_debuglevel(0)
server.login(from_add, from_pwd)
server.sendmail(from_add, [to_add], msg.as_string())
server.quit()

smtp python2.7

baga、⑨ 9 years, 5 months ago

上面的问题解决了,首先在python中,MIME的这些对象的继承关系如下。


 MIMEBase
       |-- MIMENonMultipart
           |-- MIMEApplication
           |-- MIMEAudio
           |-- MIMEImage
           |-- MIMEMessage
           |-- MIMEText
       |-- MIMEMultipart

之前使用的是MIMEApplication 对附件进行封装
现在使用MIMEBase对附件进行封装


 part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
part.set_payload(open(file, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 
msg.attach(part)

但为什么Outlook无法识别MIMEApplication还是搞不明白,后面的问题继续提问。

klairs answered 9 years, 5 months ago

Your Answer