Home  >  Q&A  >  body text

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

我用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

PHPzPHPz2766 days ago458

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 11:08:42

    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()

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:08:42

    # -*- 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下测试可以正常接收

    reply
    0
  • Cancelreply