一 发件人名称乱码问题,必须使用Header
from email.header import Header
from = ("%s<outofmemory_cn@126.com>") % (Header('OutOfMemory.CN管理员','utf-8'),)
二 邮件主题乱码问题
邮件主题乱码有可能是在某些邮箱出现,例如我遇到发给Gmail不会乱码,但是发给sina.cn的邮箱就会乱码。要解决邮件主题乱码的问题需要保证subject必须是unicode,如下:
if not isinstance(subject,unicode):
subject = unicode(subject)
msg['Subject'] = subject
三 邮件正文乱码问题
首先需要将MIMEText指定为utf-8编码,然后还要设置msg['Accept-Language']和msg['Accept-Charset']两个属性,如下:
msg = MIMEText(body,format,'utf-8')
msg["Accept-Language"]="zh-CN"
msg["Accept-Charset"]="ISO-8859-1,utf-8"
四 python完整的邮件发送代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#下面一行要设置成你自己的邮件服务器的地址以及用户名密码发件人信息
host,user,password,fromMail = smtpInfo
def sendMail(mailto,subject,body,format='plain'):
if isinstance(body,unicode):
body = str(body)
me= ("%s<"+fromMail+">") % (Header(_mailFrom,'utf-8'),)
msg = MIMEText(body,format,'utf-8')
if not isinstance(subject,unicode):
subject = unicode(subject)
msg['Subject'] = subject
msg['From'] = me
msg['To'] = mailto
msg["Accept-Language"]="zh-CN"
msg["Accept-Charset"]="ISO-8859-1,utf-8"
try:
s = smtplib.SMTP()
s.connect(host)
s.login(user,password)
s.sendmail(me, mailto, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False