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

前端 未结 2 528
甜味超标
甜味超标 2020-12-29 06:30

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

file msg.txt:
--------------------         


        
相关标签:
2条回答
  • 2020-12-29 06:38

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

    0 讨论(0)
  • 2020-12-29 06:53

    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
    
    0 讨论(0)
提交回复
热议问题