您的位置:首页 > 编程语言 > Python开发

python邮件发送(带附件,解决中文乱码问题)

2011-08-03 16:53 766 查看
#-*- encoding: utf-8 -*-

#导入smtplib和MIMEText
import smtplib
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import os.path

def mailtest(from_addr,to_addr,subject,content,attfile):
#创建一个带附件的实例
msg = MIMEMultipart()

#添加邮件内容
#注意,要指定邮件内容的编码为utf-8,否则中文会有乱码
text_msg = MIMEText(content,'plain','utf-8')
msg.attach(text_msg)

#构造附件
#注意:传入的参数attfile为unicode,否则带中文的目录或名称的文件读不出来
#      basename 为文件名称,由于传入的参数attfile为unicode编码,此处的basename也为unicode编码
basename = os.path.basename(attfile)

#注意:指定att的编码方式为gb2312
att = MIMEText(open(attfile, 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'

#注意:此处basename要转换为gb2312编码,否则中文会有乱码。
#      特别,此处的basename为unicode编码,所以可以用basename.encode('gb2312')
#            如果basename为utf-8编码,要用basename.decode('utf-8').encode('gb2312')
att["Content-Disposition"] = 'attachment; filename=%s' % basename.encode('gb2312')
msg.attach(att)

#加邮件头
msg['to'] = from_addr
msg['from'] = to_addr
#主题指定utf-8编码,否则中文会有乱码
msg['subject'] = Header(subject, 'utf-8')

#发送邮件
server = smtplib.SMTP('smpt.xxxx.cn')
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.close

if  __name__ =="__main__":
#注意:附件的路径字符串应为unicode编码
mailtest("from@xxx.cn", "to@xxx.cn", "主题", "内容", u"D:\\日志文件.txt")


最近用python写一个自动发邮件的脚本,单纯发送没有什么问题,中文乱码倒是折磨了我好长时间。最终解决的办法见下面的代码。最后测试时发现,在网页上打开邮件中文是正常显示,但是用foxmail收下来后,附件名称中的中文还是乱码。先这样了。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐