I am sending email from Python (Django). The email host is ‘smtp.gmail.com’. I am able to use special characters in the email subject when I use localhost. However, now that I am trying from the server (webfaction) I get an error “UnicodeDecodeError: ‘ascii’ codec can’t decode byte…” In the email template I use hex codes, but they don’t work for the subject (they aren’t translated). What to do?
# coding=UTF-8
...
subject = "æøå"
c = {}
t_html = loader.get_template(template_html)
t_text = loader.get_template(template_txt)
e = EmailMultiAlternatives(subject, t_text.render(Context(c)), from_email, [to_email])
e.attach_alternative(t_html.render(Context(c)), "text/html")
e.send()
If you’re using Python 2, I’d suggest prepending your string with
u:(I know the
coding“magic comment” is supposed to handle that automatically, but from experience I can say it does not always work)Update: for future reference, it’s also important to ensure the production environment supports the same encoding used on development. It should be fine with
UTF-8(it’s supported everywhere), but if you were to edit your source files under Windows (Cp1252) and then deploy in a UNIX server, the Python interpreter might not be able to read them, regardless of the presence ofcoding.