解决python发送邮件乱码

一.邮件主题乱码

1.打开python的Lib文件夹下的 mimetypes.py 文件,找到大概256行的

‘default_encoding = sys.getdefaultencoding()’。

在这行前面添加三行,并且注释4行代码

                #try:
                #    ctype = ctype.encode(default_encoding) # omit in 3.x!
                #except UnicodeEncodeError:
                #    pass
                else:
                    yield ctype
                i += 1

                if sys.getdefaultencoding() != 'gbk':  
                    reload(sys)  
                    sys.setdefaultencoding('gbk')
                default_encoding = sys.getdefaultencoding()


2.在代码中加入下面片段

reload(sys) 
sys.setdefaultencoding('gb18030')

二.邮件内容乱码

在代码中对内容做如下处理

msg = MIMEText(content,format,'gbk')

三.详细发送邮件代码

#!/usr/bin/python
#coding:utf-8 
 
import smtplib
from email.mime.text import MIMEText
import sys 
 
#邮箱服务器地址
mail_host = 'smtp.163.com'
#邮箱用户名
mail_user = 'XXX'
#邮箱密码
mail_pass = 'XXX'
mail_postfix = '163.com'
 
def send_mail(to_list,subject,content):
    format='plain'
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content,format,'gbk')
    reload(sys) 
    sys.setdefaultencoding('gb18030')
    if not isinstance(subject,unicode):
        subject = unicode(subject)
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = to_list 
    msg['Accept-Language']='zh-CN'
    msg['Accept-Charset']='ISO-8859-1,utf-8'
 
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False
 
if __name__ == "__main__":
    send_mail(sys.argv[1], sys.argv[2], sys.argv[3])

四.收发件人中文乱码

可参考此链接:http://blog.csdn.net/zm2714/article/details/8134118


五.测试邮件发送

python email_test.py '[email protected]' '测试邮件' '这个邮件是测试用'

解决python发送邮件乱码_第1张图片

你可能感兴趣的:(python)