Encoding of headers in MIMEText

人走茶凉 提交于 2019-11-29 10:58:33

I found the solution. Email headers containing non ascii characters need to be encoded as per RFC 2047. In Python this means using email.header.Header instead of a regular string for header content (see http://docs.python.org/2/library/email.header.html). The right way to write the above example is then

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()

The subject string will be encoded in the email as

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

The fact the in python 2.x the previous code was working for me is probably related to the mail client being able to interpret the wrongly encoded header.

         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()

I've found that replacing

msg['Subject'] = subject

with

msg.add_header('Subject', subject)

works for getting UTF-8 to display. If you want another character-set, you can do that, too. try help(msg.add_header) to see the docs on that (replace the value, that is subject with a tuple containing three elements: (charset, language, value).

Anyway, this seems a little simpler than the other method—so, I thought I'd mention it. I decided to try this since add_header seems to work more often for the 'reply-to' header than just doing msg["reply-to"]=your_reply_to_email. So, I thought maybe it would be better for subjects, too—and the docs said it supported UTF-8 by default (which I tested, and it worked).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!