MIMEText UTF-8 encode problems when sending email

前端 未结 2 912
时光取名叫无心
时光取名叫无心 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())
    
    0 讨论(0)
  • 2020-12-13 21:46

    I've improved the answer with other way to connect with the server and loggin, because the other way i had the problem to authenticate with the application and people can see all the libraries that should be use

    from email.mime.text import MIMEText
    from email.header import Header
    import smtplib
    
    user='email1@teste.com'
    pwd='password'
    server = smtplib.SMTP('smtp.office365.com', 587) #it works with outlook
    server.ehlo()
    server.starttls()
    server.login(user, pwd)
    assunto = 'Teste'
    para = 'email2@teste.com'
    texto = 'Niterói é uma cidade incrível '
    corpo = MIMEText(texto, 'plain', 'utf-8')
    corpo['From'] = user
    corpo['To'] = para
    corpo['Subject'] = Header(assunto, 'utf-8')
    try:
        server.sendmail(user, [para], corpo.as_string())
        print('email was sent')
    except:
        print('error')
    server.quit()
    
    0 讨论(0)
提交回复
热议问题