python - Encoding of headers in MIMEText -


i'm using mimetext create email scratch in python 3.2, , have trouble creating messages non-ascii characters in subject.

for example

from email.mime.text import mimetext body = "some text" subject = "» subject"                   # first char non-ascii msg = mimetext(body,'plain','utf-8') msg['subject'] = subject                   # <<< problem here text = msg.as_string() 

the last line gives me error

unicodeencodeerror: 'ascii' codec can't encode character '\xbb' in position 0: ordinal not in range(128) 

how tell mimetext subject not ascii ? subject.encode('utf-8') doesn't @ all, , anyway i've seen people using unicode strings no problems in other answers (see example python - how send utf-8 e-mail?)

edit: i'd add same code doesn't give error in python 2.7 (thought doesn't mean result correct).

i found solution. email headers containing non ascii characters need encoded per rfc 2047. in python means using email.header.header instead of regular string header content (see http://docs.python.org/2/library/email.header.html). right way write above example then

from email.mime.text import mimetext email.header import header body = "some text" subject = "» subject"                    msg = mimetext(body,'plain','utf-8') msg['subject'] = header(subject,'utf-8') text = msg.as_string() 

the subject string encoded in email

=?utf-8?q?=c2=bb_my_subject?= 

the fact in python 2.x previous code working me related mail client being able interpret wrongly encoded header.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -