以下是我的代码的一部分,它发送了一封电子邮件:
servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.login(user, usenha)
assunto = str(self.lineEdit.text())
para = str(globe_email)
texto = self.textEdit.toPlainText()
textos = str(texto)
corpo = MIMEText(textos.encode('utf-8'), _charset='utf-8')
corpo['From'] = user
corpo['To'] = para
corpo['Subject'] = assunto
servidor.sendmail(user, [para], corpo.as_string())
除了主题部分外,一切都很好。 当我尝试发送带有特殊字符的字符串(例如“ação”)时,会引发此错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
如何在MIMEText的主题中发送带有特殊字符的电子邮件?
答案 0 :(得分:38)
似乎在python3中,需要Header
个对象将Subject
编码为“utf-8”:
>>> from email.mime.text import MIMEText
>>> from email.header import Header
>>> s = 'ação'
>>> m = MIMEText(s.encode('utf-8'), 'plain', 'utf-8')
>>> m['Subject'] = Header(s, 'utf-8')
>>> m.as_string()
'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nSubject: =?utf-8?b?YcOnw6Nv?=\n\nYcOnw6Nv\n'
因此原始脚本将成为:
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.encode('utf-8'), 'plain', 'utf-8')
corpo['From'] = user
corpo['To'] = para
corpo['Subject'] = Header(assunto, 'utf-8')
servidor.sendmail(user, [para], corpo.as_string())
答案 1 :(得分:1)
我用其他方法连接服务器和登录以改善答案,因为用另一种方法我无法通过应用程序进行身份验证,并且人们可以看到所有应该使用的库
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()