MIMEText UTF-8 encode problems when sending email

前端 未结 2 915
时光取名叫无心
时光取名叫无心 2020-12-13 21:16

Here is a part of my code which sends an email:

servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.login(user, usenha)
assunto = str(self.lineEd         


        
2条回答
  •  死守一世寂寞
    2020-12-13 21:23

    It seems that, in python3, a Header object is needed to encode a Subject as utf-8:

    # -*- coding: utf-8 -*-
    from email.mime.text import MIMEText
    from email.header import Header
    s = 'ação'
    m = MIMEText(s, 'plain', 'utf-8')
    m['Subject'] = Header(s, 'utf-8')
    print(repr(m.as_string()))
    

    Output:

    'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nSubject: =?utf-8?b?YcOnw6Nv?=\n\nYcOnw6Nv\n
    

    So the original script would become:

    servidor = smtplib.SMTP()
    servidor.connect(HOST, PORT)
    servidor.login(user, usenha)
    assunto = str(self.lineEdit.text())
    para = str(globe_email)             
    texto = str(self.textEdit.toPlainText())
    corpo = MIMEText(texto, 'plain', 'utf-8')
    corpo['From'] = user
    corpo['To'] = para
    corpo['Subject'] = Header(assunto, 'utf-8')
    servidor.sendmail(user, [para], corpo.as_string())
    

提交回复
热议问题