Encoding mail subject (SMTP) in Python with non-ASCII characters

Rakesh picture Rakesh · Aug 2, 2011 · Viewed 16.3k times · Source

I am using Python module MimeWriter to construct a message and smtplib to send a mail constructed message is:

file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<[email protected]>
to: [email protected]
subject: 主題

Content-Type: text/plain;charset=utf-8

主題

I use the code below to send a mail:

import smtplib
s=smtplib.SMTP('smtp.abc.com')
toList = ['[email protected]']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('[email protected]',toList,msg)

I get mail body correctly but subject is not proper,

subject: some junk characters

主題           <- body is correct.

Please suggest? Is there any way to specify the decoding to be used for the subject also, as being specified for the body. How can I get the subject decoded correctly?

Answer

S&#233;rgio picture Sérgio · Oct 22, 2012

From http://docs.python.org/library/email.header.html

from email.message import Message
from email.header import Header
msg = Message()
msg['Subject'] = Header('主題', 'utf-8')
print msg.as_string()

Subject: =?utf-8?b?5Li76aGM?=

more simple:

from email.header import Header
print Header('主題', 'utf-8').encode()

=?utf-8?b?5Li76aGM?=