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('[email protected]', 'passwd')
msg = MIMEMultipart('alternative')
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = sendTo
msg.attach(MIMEText(htmlBody, 'html', 'utf-8'))
server.sendmail('[email protected]', '[email protected]', msg.as_string())

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

python smtp

Jamky 10 years, 8 months ago

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 = '[email protected]'
TO = ['[email protected]']

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()
邪恶D小狼 answered 10 years, 8 months ago

Your Answer