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

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?



Solution 1:[1]

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?=

Solution 2:[2]

The subject is transmitted as an SMTP header, and they are required to be ASCII-only. To support encodings in the subject you need to prefix the subject with whatever encoding you want to use. In your case, I would suggest prefix the subject with ?UTF-8?B? which means UTF-8, Base64 encoded.

In other words, I believe your subject header should more or less look like this:

Subject: =?UTF-8?B?JiMyMDAyNzsmIzM4OTg4Ow=?=

In PHP you could go about it like this:

// Convert subject to base64
$subject_base64 = base64_encode($subject);
fwrite($smtp, "Subject: =?UTF-8?B?{$subject_base64}?=\r\n");

In Python:

import base64
subject_base64 = base64.encodestring(subject).strip()
subject_line = "Subject: =?UTF-8?B?%s?=" % subject_base64

Solution 3:[3]

In short, if you use the EmailMessage API, you should code like this:

from email.message import EmailMessage
from email.header import Header
msg = EmailMessage()
msg['Subject'] = Header('??', 'utf-8').encode()

Answer from @Sérgio cannot be used in the EmailMessage API, cause only string object can be assigned to EmailMessage()["Subject"], but not an email.header.Header object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jimm Chen
Solution 3 C.K.