gpt4 book ai didi

python - 发送电子邮件时 MIMEText UTF-8 编码问题

转载 作者:太空狗 更新时间:2023-10-29 17:00:16 24 4
gpt4 key购买 nike

这是我发送电子邮件的代码的一部分:

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())

除了 Subject 部分,一切正常。当我尝试发送带有特殊字符(例如“ação”)的字符串时,它会引发此错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)

如何发送在 MIMEText 主题中包含特殊字符的电子邮件?

最佳答案

看来,在 python3 中,一个 Header需要对象将 Subject 编码为 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()))

输出:

'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, 'plain', 'utf-8')
corpo['From'] = user
corpo['To'] = para
corpo['Subject'] = Header(assunto, 'utf-8')
servidor.sendmail(user, [para], corpo.as_string())

关于python - 发送电子邮件时 MIMEText UTF-8 编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com