Encode MIMEText as quoted printables

后端 未结 3 2082
情书的邮戳
情书的邮戳 2020-12-31 08:53

Python supports a quite functional MIME-Library called email.mime.

What I want to achieve is to get a MIME Part containing plain UTF-8 text to be encod

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 09:35

    Adapted from issue 1525919 and tested on python 2.7:

    from email.Message import Message
    from email.Charset import Charset, QP
    
    text = "\xc3\xa1 = \xc3\xa9"
    msg = Message()
    
    charset = Charset('utf-8')
    charset.header_encoding = QP
    charset.body_encoding = QP
    
    msg.set_charset(charset)
    msg.set_payload(msg._charset.body_encode(text))
    
    print msg.as_string()
    

    will give you:

    MIME-Version: 1.0
    Content-Type: text/plain; charset="utf-8"
    Content-Transfer-Encoding: quoted-printable
    
    =C3=A1 =3D =C3=A9
    

    Also see this response from a Python committer.

提交回复
热议问题