在Python 3.1中,smtplib发送带有unicode字符的邮件时出现问题
您好,我在unicode电子邮件中遇到了这个问题,当我试图用西班牙语发送诸如“Añadir”或其他系统崩溃的单词时,我尝试了这个链接上的内容:但不起作用 这是我的错误代码:在Python 3.1中,smtplib发送带有unicode字符的邮件时出现问题,unicode,python-3.x,smtplib,Unicode,Python 3.x,Smtplib,您好,我在unicode电子邮件中遇到了这个问题,当我试图用西班牙语发送诸如“Añadir”或其他系统崩溃的单词时,我尝试了这个链接上的内容:但不起作用 这是我的错误代码: server.sendmail(frm, to, msg.as_string()) g.flatten(self, unixfrom=unixfrom) self._write(msg) self._write_headers(msg) header_name=h) self.append(s, charset, error
server.sendmail(frm, to, msg.as_string())
g.flatten(self, unixfrom=unixfrom)
self._write(msg)
self._write_headers(msg)
header_name=h)
self.append(s, charset, errors)
input_bytes = s.encode(input_charset, errors)
UnicodeEncodeError:“ascii”编解码器无法对位置7中的字符“\xf1”进行编码:序号不在范围内(128)
这是服务器上的代码:
msg = MIMEMultipart('alternative')
frm = "sales@bmsuite.com"
msg['FROM'] = frm
to = "info@bmsuite.com"
msg['To'] = to
msg['Subject'] = "Favor añadir esta empresa a la lista"
_attach = MIMEText("""Nombre:Prueba; Dirección:Calle A #12.""".encode('utf-8'), _charset='utf-8')
msg.attach(_attach)
server.sendmail(frm, to, msg.as_string())
server.quit()
提前感谢。我解决了它,解决方案如下:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
frm = "xxxx@xxxxxx.com"
msg = MIMEMultipart('alternative')
msg.set_charset('utf8')
msg['FROM'] = frm
bodyStr = ''
to = "xxxx@xxxxxx.com"
#This solved the problem with the encode on the subject.
msg['Subject'] = Header(
body.getAttribute('subject').encode('utf-8'),
'UTF-8'
).encode()
msg['To'] = to
# And this on the body
_attach = MIMEText(bodyStr.encode('utf-8'), 'html', 'UTF-8')
msg.attach(_attach)
server.sendmail(frm, to, msg.as_string())
server.quit()
希望这有帮助!
谢谢 您只需使用:
msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")
但无论哪种方式,如果您的
frm=”仍然存在问题xxxx@xxxxxx.com“
或至=”xxxx@xxxxxx.com“
包含unicode字符。您不能在那里使用页眉。我在()上找到了一个非常简单的解决方法:
在sendmail命令的末尾。我可能遗漏了一些内容,但没有看到“body”变量赋值。另外:
server
未定义。
msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()
msg.encode("utf8")