smtplib在Python 3.1中使用unicode字符发送邮件的问题

hid*_*ura 15 unicode smtplib python-3.x

您好我有unicode电子邮件的问题,当我尝试发送西班牙语单词时:"Añadir"或其他系统崩溃,我尝试在此链接上说的内容:Python 3 smtplib发送unicode字符而不是工作.

这是我的错误代码:

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)
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

提前致谢.

小智 23

你可以改为使用:

msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")
Run Code Online (Sandbox Code Playgroud)

但无论哪种方式,如果你frm = "xxxx@xxxxxx.com"或者使用to = "xxxx@xxxxxx.com"unicode字符,你仍会遇到问题.你不能在那里使用Header.


hid*_*ura 19

我解决了,解决方法是:

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()
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!谢谢!

  • 我可能错过了一些东西,但我没有看到'body'变量赋值. (3认同)

jep*_*oo1 8

我在这里找到了一个非常简单的解决方法(https://bugs.python.org/issue25736):

msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()
Run Code Online (Sandbox Code Playgroud)

因此,要以正确的方式对这些 un​​icode 字符进行编码,请添加

msg.encode("utf8") 
Run Code Online (Sandbox Code Playgroud)

在 sendmail 命令的末尾。