Issue with smtplib sending mail with unicode characters in Python 3.1

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 = "[email protected]"
msg = MIMEMultipart('alternative')

msg.set_charset('utf8')

msg['FROM'] = frm

bodyStr = ''
to = "[email protected]"
#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!


I found a very easy workaround here on (https://bugs.python.org/issue25736):

msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()

So, to encode those unicode characters the right way, add

msg.encode("utf8") 

at the end of the sendmail command.


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 = "[email protected]" or to = "[email protected]" constains unicode characters. You can't use Header there.