MIMEText UTF-8 encode problems when sending email

前端 未结 2 914
时光取名叫无心
时光取名叫无心 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: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()
    

提交回复
热议问题