http://www.meiyear.com/wordpress/archives/97
昨天有一个朋友告诉我,他使用python发送邮件,附件名为乱码
1.他的头部定义是#-*- encoding: utf-8 -*-
2.代码中指定的是GB2312导致了邮件乱码
只要把代码部份中的gb2312改成UTF-8就全部正常
以下为解决部份的代码片段
[python]
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
import smtplib,mimetypes
from email.mime.multipart import MIMEMultipart #多个MIME对象的集合
from email.mime.text import MIMEText #MIME文本对象
from email.mime.p_w_picpath import MIMEImage #MIME二进制文件对象
from email import utils
from email import encoders
from email.header import Header
import os.path
import datetime
import time
sender = ‘dingyangfan@163.com’ #发件人邮箱
smtpserver = ‘smtp.163.com’ #邮件服务器
username = ‘dingyangfan’ #发件人邮箱用户名
password = ‘*****’ #发件人邮箱密码
mailHead = “邮件”
mailBody = “邮件正文”
#收件人列表
tolist = (’8094731@qq.com’, ‘sghsnmh@126.com’)
msgRoot = MIMEMultipart()
attText = MIMEText(mailBody, ‘plain’,'utf-8′)
msgRoot.attach(attText) #添加邮件正文
msgRoot['from'] = sender #发件人
msgRoot['Subject'] = Header(mailHead, ‘utf-8′) #邮件
msgRoot['Date'] = time.ctime(time.time()) #设置时间
#构造附件(附件路径出现中文,会提示编码错误!!!!!!)
rarFilePath = u”解决_ubuntu_安装后字体_发虚_模糊.doc”
att = MIMEText(open(rarFilePath, ‘rb’).read(), ‘base64′, ‘UTF-8′)
att["Content-Type"] = ‘application/octet-stream;name=”%s”‘% Header(rarFilePath,’UTF-8′)
att["Content-Disposition"] = ‘p_w_upload;filename= %s’ % Header(rarFilePath, ‘UTF-8′)
msgRoot.attach(att)
#群发邮件
smtp = smtplib.SMTP(smtpserver, 25)
smtp.login(username, password)
msgRoot['to'] = ’8094731@qq.com’
smtp.sendmail(sender, tolist, msgRoot.as_string())
time.sleep(5) #休眠5秒
smtp.quit() #断开与服务器的连接