Encode MIMEText as quoted printables

后端 未结 3 1957
情书的邮戳
情书的邮戳 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:23

    You do not need your hack:

    import email
    
    # Construct a new charset which uses Quoted Printables (base64 is default)
    cs = email.charset.Charset('utf-8')
    cs.body_encoding = email.charset.QP
    
    m = email.mime.text.MIMEText(u'This is the text containing ünicöde', 'plain', _charset=cs)
    
    print(m.as_string())
    
    0 讨论(0)
  • 2020-12-31 09:26

    Okay, I got one solution which is very hacky, but at least it leads into some direction: MIMEText assumes base64 and I don't know how to change this. For this reason I use MIMENonMultipart:

    import email.mime, email.mime.nonmultipart, email.charset
    m=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')
    
    #Construct a new charset which uses Quoted Printables (base64 is default)
    cs=email.charset.Charset('utf-8')
    cs.body_encoding = email.charset.QP
    
    #Now set the content using the new charset
    m.set_payload(u'This is the text containing ünicöde', charset=cs)
    

    Now the message seems to be encoded correctly:

    Content-Type: text/plain; charset="utf-8"
    MIME-Version: 1.0
    Content-Transfer-Encoding: quoted-printable
    
    This is the text containing =C3=BCnic=C3=B6de
    

    One can even construct a new class which hides the complexity:

    class MIMEUTF8QPText(email.mime.nonmultipart.MIMENonMultipart):
      def __init__(self, payload):
        email.mime.nonmultipart.MIMENonMultipart.__init__(self, 'text', 'plain',
                                                          charset='utf-8')
    
        utf8qp=email.charset.Charset('utf-8')
        utf8qp.body_encoding=email.charset.QP
    
        self.set_payload(payload, charset=utf8qp) 
    

    And use it like this:

    m = MIMEUTF8QPText(u'This is the text containing ünicöde')
    m.as_string()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题