解决python发送邮件乱码问题
使用python发邮件很简单,但是遇到乱码问题很烦恼。 乱码问题有几种:有发件人名称乱码,有标题乱码,也有正文乱码的问题。
一、发件人名称乱码
要解决发件人名称乱码问题,必须使用Header,如下代码:
1from email.header import Header
2from = ("%s") % (Header('361way.COM管理员','utf-8'),)
通过这样设置发件人之后,发件人的显示就不会有乱码的现象了。
二、subject主题乱码
邮件主题乱码有可能是在某些邮箱出现,例如我遇到发给163不会乱码,但是发给qq的邮箱就会乱码。要解决邮件主题乱码的问题需要保证subject必须是unicode,如下:
1#code from www.361way.com
2if not isinstance(subject,unicode):
3 subject = unicode(subject)
4msg['Subject'] = subject
三、body正文乱码
解决邮件正文乱码问题,首先需要将MIMEText指定为utf-8编码,然后还要设置msg[‘Accept-Language’]和msg[‘Accept-Charset’]两个属性,如下代码片段:
1msg = MIMEText(body,format,'utf-8')
2msg["Accept-Language"]="zh-CN"
3msg["Accept-Charset"]="ISO-8859-1,utf-8"
解决了以上三个问题,邮件乱码问题就不存在了,下面是完整的发邮件代码:
1#code from www.361way.com
2import smtplib
3from email.mime.text import MIMEText
4from email.header import Header
5#下面一行要设置成你自己的邮件服务器的地址以及用户名密码发件人信息
6host,user,password,fromMail = smtpInfo
7def sendMail(mailto,subject,body,format='plain'):
8 if isinstance(body,unicode):
9 body = str(body)
10 me= ("%s") % (Header(_mailFrom,'utf-8'),)
11 msg = MIMEText(body,format,'utf-8')
12 if not isinstance(subject,unicode):
13 subject = unicode(subject)
14 msg['Subject'] = subject
15 msg['From'] = me
16 msg['To'] = mailto
17 msg["Accept-Language"]="zh-CN"
18 msg["Accept-Charset"]="ISO-8859-1,utf-8"
19 try:
20 s = smtplib.SMTP()
21 s.connect(host)
22 s.login(user,password)
23 s.sendmail(me, mailto, msg.as_string())
24 s.close()
25 return True
26 except Exception, e:
27 print str(e)
28 return False
上面的程序测试过发送到Gmail,Sina,QQ,163以及HotMail,均没有乱码问题。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-mail-garbled/5494.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.