Issue with smtplib sending mail with unicode characters in Python 3.1

对着背影说爱祢 提交于 2019-11-28 09:50:01

You can instead just use:

msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")

But either way you still have issues if your frm = "xxxx@xxxxxx.com" or to = "xxxx@xxxxxx.com" constains unicode characters. You can't use Header there.

hidura

I solved it, the solution is this:

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

frm = "xxxx@xxxxxx.com"
msg = MIMEMultipart('alternative')

msg.set_charset('utf8')

msg['FROM'] = frm

bodyStr = ''
to = "xxxx@xxxxxx.com"
#This solved the problem with the encode on the subject.
msg['Subject'] = Header(
    body.getAttribute('subject').encode('utf-8'),
    'UTF-8'
).encode()

msg['To'] = to

# And this on the body
_attach = MIMEText(bodyStr.encode('utf-8'), 'html', 'UTF-8')        

msg.attach(_attach)

server.sendmail(frm, to, msg.as_string())

server.quit()

Hope this helps! Thanks!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!