Python发送中文邮件乱码的一个解决方法

1:将MIMEText 指定为 utf-8的编码格式

msg = MIMEText(content, text_subtype, 'utf-8')

msg["Accept-Language"] = "zh-CN"

msg["Accept-Charset"] = "ISO-8859-1,utf-8"

2:如果主题也乱码,将主题也指定为 utf-8的编码格式

msg['Subject'] = Header(subject, 'utf-8')

下面附上全部代码

defSendMail_DB(subject,content):

fromsmtplibimportSMTP

fromemail.mime.textimportMIMEText

fromemail.headerimportHeader

SMTPserver='smtp.xxxxxx.com'

sender='xxxx@xxxxxx.com'

destination=['xxx@xxxxxx.com','xxxxxx@163.com']

USERNAME="xxxx@xxxxxx.com"

PASSWORD="xxxxx"

# typical values for text_subtype are plain, html, xml

text_subtype='plain'

try:

msg=MIMEText(content, text_subtype,'utf-8')

msg["Accept-Language"]="zh-CN"

msg["Accept-Charset"]="ISO-8859-1,utf-8"

msg['Subject']=Header(subject,'utf-8')

msg['From']=sender

msg['To']=','.join(destination)

server=SMTP(SMTPserver,587)

server.ehlo()

server.starttls()

server.set_debuglevel(False)

server.login(USERNAME, PASSWORD)

server.sendmail(sender, destination, msg.as_string())

server.close()

print"Mail Send Successful"

exceptException, exc:

print"mail failed; %s"%str(exc)# give a error message

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180228G0GZ5Z00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券