3

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() 
user984003
  • 28,050
  • 64
  • 189
  • 285
  • I found this http://stackoverflow.com/a/517974/230884 useful for my cases. Worth a look. I also agree with `mgibsonbr`. the `u` doesn't solve everything. Some other characters will fail. – CppLearner Dec 27 '12 at 08:18
  • @CppLearner What I meant was, just using `coding` **without** also using `u` does not always work. Anyway, if the environment does not support `coding` and/or the specified encoding, there's no way it can correctly read the source file. Better to use hex codes or `\uXXXX`. – mgibsonbr Dec 27 '12 at 08:24
  • @mgibsonbr I thought the opposite. Maybe it's just my environment. I've done as you suggested but that combination still didn't work. So at the end, I've to use the solution I linked above. I know so little about unicode (which is a shame lol). Hence, `useful for my cases` :) cheer. – CppLearner Dec 27 '12 at 08:27
  • @CppLearner you're right, the opposite is true too. See my updated answer. And don't worry, unicode is a tricky subject, I'm working with it for years and still have a lot to learn (normalization, for instance, is unbeknownst to me). – mgibsonbr Dec 27 '12 at 08:36

1 Answers1

5

If you're using Python 2, I'd suggest prepending your string with u:

subject = 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 of coding.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112