MIMEText UTF-8 encode problems when sending email
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='[email protected]'
pwd='password'
server = smtplib.SMTP('smtp.office365.com', 587) #it works with outlook
server.ehlo()
server.starttls()
server.login(user, pwd)
assunto = 'Teste'
para = '[email protected]'
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()
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())