【问题标题】:Issue with smtplib sending mail with unicode characters in Python 3.1smtplib 在 Python 3.1 中发送带有 unicode 字符的邮件的问题
【发布时间】:2012-01-09 21:54:47
【问题描述】:

您好,我在使用 unicode 电子邮件时遇到了这个问题,当我尝试用西班牙语发送诸如“Añadir”之类的单词或其他系统崩溃时,我尝试了此链接上所说的内容:Python 3 smtplib send with unicode characters 并且不起作用.

这是我的错误代码:

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' codec can't encode character '\xf1' in position 7: ordinal not in range(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()

提前致谢。

【问题讨论】:

    标签: unicode python-3.x smtplib


    【解决方案1】:

    您可以改为使用:

    msg = MIMEText(message, _charset="UTF-8")
    msg['Subject'] = Header(subject, "utf-8")
    

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

    【讨论】:

      【解决方案2】:

      我解决了,解决办法是这样的:

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

      希望这会有所帮助! 谢谢!

      【讨论】:

      • 我可能遗漏了一些东西,但我没有看到“body”变量赋值。
      • 另外:server 未定义。
      【解决方案3】:

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

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

      所以,要正确编码这些 un​​icode 字符,请添加

      msg.encode("utf8") 
      

      在 sendmail 命令的末尾。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 2012-12-12
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        相关资源
        最近更新 更多