python smtp模块发送邮件显示乱码的问题,smtp模块文本编码的选择

Cooper_Lannik
  • 14

我用python的smtp模块登陆QQ邮箱发邮件给用户,邮件内容和标题都是UTF-8编码,并且在MIME中设置了Content-Type为text/html;charset=utf-8
问题重现:用户收到的邮件大部分是乱码,QQ邮箱显示正常,163系乱码,大部分企业自用邮箱估计也是乱码
问题定位:请问在smtp模块中怎样选择编码?
经测试python的smtp不能发送unicode(对UTF8文本进行decode)
自助:在163中可以手动切换为utf8编码,这样可以正确显示,考虑到163的默认编码为GB2312,我把邮件内容和标题改为GB2312编码后发到163,但依旧是乱码

请问大家有没有类似的经验可以分享一下?

备注:
1.smtp的server是QQ企业邮箱
2.感谢theo的回答,但是对我貌似没起作用
3.补上我的原代码:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
server = smtplib.SMTP()
server.connect('smtp.exmail.qq.com', '25')
server.login('myemail@qq.com', 'passwd')
msg = MIMEMultipart('alternative')
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = 'myemail@qq.com'
msg['To'] = sendTo
msg.attach(MIMEText(htmlBody, 'html', 'utf-8'))
server.sendmail('myemail@qq.com', 'target@fac.com', msg.as_string())

根据theo的回答,应该在最后一行处改为msg.as_string().encode('ascii')
但是会报错,无法decode和encode

回复
阅读 20.8k
3 个回答
Theo
  • 2.6k
✓ 已被采纳

Working example,主要是创建MIME对象,使用utf-8编码:

# -*- coding: utf-8 -*-

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

SERVER = 'localhost'
FROM = 'blah@blah.com'
TO = ['blah2@blah.com']

SUBJECT = u'测试UTF8编码'
TEXT = u'ABCDEFG一二三四五六七'

msg = MIMEMultipart('alternative')
# 注意包含了非ASCII字符,需要使用unicode
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ', '.join(TO)
part = MIMEText(TEXT, 'plain', 'utf-8')
msg.attach(part)

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, msg.as_string().encode('ascii'))
server.quit()
someone
  • 2
新手上路,请多包涵

part=MIMEText(htmlBody, 'html', 'utf-8')
part.add_header("Content-Type",'text/plain; charset="utf-8"')

指定MIMETEXT的头信息里面字符集是utf-8就可以了

sailaway
  • 1
新手上路,请多包涵
# -*- coding: utf-8 -*-

import smtplib

mail_server="smtp.exmail.qq.com"
mail_user="web@test.com"
mail_psw="psw"
mail_port=465
def sendMail(content,subject="subject",send_to="user@test.com"):
  server = smtplib.SMTP_SSL()
  server.connect(mail_server, mail_port)
  server.login(mail_user,mail_psw)
  msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s"% (mail_user, send_to,subject,content))
  server.sendmail(mail_user, send_to, msg)

if __name__ == "__main__":
  sendMail("test send mail测试中文")

python 2.7下测试可以正常接收

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏