I use MIMEText to create email from scratch in Python 3.2, and I'm having trouble creating messages with non-ascii characters in the subject.
for instance
from email.mime.text import MIMEText
body = "Some text"
subject = "» My Subject"
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = subject
text = msg.as_string()
The last line gives me an error
UnicodeEncodeError: 'ascii' codec can't encode character '\xbb' in position 0: ordinal not in range(128)
How to tell MIMEText that the object is not ascii? subject.encode('utf-8')doesn’t help at all, and in any case I saw people using unicode strings without problems in other answers (see, for example, Python - How to send utf-8 e-mail? )
Edit: I would like to add that the same code does not give any error in Python 2.7 (it is believed that this does not mean that the result is correct).
source
share