python 发送带附件的邮件,收到的附件名都变成了tcmime.1774.1903.2076.bin格式,怎么回事呢?

#!/usr/bin/env python
#coding=utf-8
import smtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendEmail(sub,content,path):
#收件人/发给谁
mailto_list = ["[email protected]"]
#设置发送邮件的服务器、用户名、口令及邮箱后缀
mail_host = "mail.sf-auto.com"
mail_user = "yaopeiyun"
mail_pass = "woyigeren7799@"
mail_postfix = "sf-auto.com"
#构建附件实例
msg = MIMEMultipart()
#邮件头
me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(mailto_list)
#构造MIMEText对象为邮件显示内容
text = MIMEText(content,_subtype='plain',_charset='gb2312')
msg.attach(text)
#添加附件
f = open(path,'rb')
img = MIMEText(f.read(),'base64','gb2312')
img["Content-Type"] = 'application/octet-stream'
img["Content-Disposition"] = 'attachment,filename="hdrCount.txt"'
f.close()
msg.attach(img)

#发送邮件
try:
mysmtp = smtplib.SMTP()
mysmtp.connect(mail_host)
mysmtp.login(mail_user,mail_pass)
mysmtp.sendmail(me,mailto_list,msg.as_string())
print 'send sucess'
mysmtp.close()
except Exception,e:
print str(e)
if __name__ == '__main__':
sendEmail('test mail','its a python test email','D:\\csgc3000\\var\\log\\netserver.log')
我只需要发送.txt的文件就行

img["Content-Disposition"] = 'attachment,filename="hdrCount.txt"'这行改为:
img["Content-Disposition"] = 'attachment,filename=%s' % string.encode("uff-8")
也就是说对你发送的内容需要进行uft-8编码。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-28
img["Content-Disposition"] = 'attachment,filename="hdrCount.txt"'
这句话改为:img["Content-Disposition"] = 'attachment;filename="hdrCount.txt"'
ps:attachment后面是分号不是逗号~细心很重要啊~我也是检查了好久才发现。。
第2个回答  2014-06-13

如果只是文本文件,可以不用构造MIME对象。

# read the text file
msg = open(your_text_file, 'r').read()

# maybe you need to add some splitter letter 
# at the front and at the end of text file

# here to prepare for smtp connection
mysmtp.sendmail(me, mailto_list,msg)