Header Encoding in MIMEText

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"                   # first char is non-ascii
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = subject                   # <<< Problem probably here
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).

+5
source share
2 answers

. , ascii, RFC 2047. Python email.header.Header (. http://docs.python.org/2/library/email.header.html). :

from email.mime.text import MIMEText
from email.header import Header
body = "Some text"
subject = "» My Subject"                   
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject,'utf-8')
text = msg.as_string()

=?utf-8?q?=C2=BB_My_Subject?=

, python 2.x , , , .

+9
         Esta funsion manda un email a un solo correo si alguien quiere la funsión que          mande a varios email tambien la tengo.
         text = ('Text')
         mensaje = MIMEText(text,'plain','utf-8')
         mensaje['From']=(remitente)
         mensaje['Subject']=('Asunto')
         mailServer = smtplib.SMTP('xxx.xxx.mx')
         mailServer.ehlo()
         mailServer.starttls()
         mailServer.ehlo()

         mailServer.sendmail(remitente,destinatario, mensaje.as_string())
                            mailServer.close()
0

All Articles