在Python 2.6中发送包含UTF-8字符串的邮件时出现问题

0 投票
1 回答
821 浏览
提问于 2025-04-17 19:34

下面是相关的代码片段:

def send_mail_cloned():
    COMMASPACE = ', '
    sender='xxx@xyz.com'
    send_open_mail_to='xxx@xyz.com'
    # Create the container (outer) email message.
    msg = MIMEMultipart()
    msg.set_charset("utf-8")
    msg['Subject'] = 'Test'
    msg['From'] = sender
    msg['To'] = COMMASPACE.join(send_open_mail_to)

    text="""
    <html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       <title>html title</title>
       <style type="text/css" media="screen">
           table{
                 background-color: #AAD373;
                 empty-cells:hide;
           }
           td.cell{
                 background-color: white;
           }
       </style>
     </head>
     <body>"""

    text+="""<p><BR>Hi, <BR>Please find below table for Cloned JIRA's:<BR></p>
         <table style="border: blue 1px solid;">

             <tr><td class="cell">JIRA Link</td><td class="cell">PRISM URL</td><td class="cell">CR Title</td></tr>"""
for key,value in jira_cr_cloned_dict.items():
             CR_title=value[1].decode('utf-8')
             text+="""<tr><td class="cell">%s</td><td class="cell">%s</td><td class="cell">%s</td></tr>""" %(key,value[0],CR_title)
text+=”””</table></body>
     </html>”””
    HTML_BODY = MIMEText(text, 'html','utf-8')
    Encoders.encode_7or8bit(HTML_BODY)
    msg.attach(HTML_BODY)
    # Send the email via our own SMTP server.
    s = smtplib.SMTP('localhost')
    s.sendmail(sender, send_open_mail_to, msg.as_string())
    s.quit()

这是填充 jira_cr_cloned_dict 的代码部分:

CR_title=CR_detail['Title'].encode('utf-8')
print ('CR title in PRISM: %s\n'%CR_title)
CR_list=[prism_url[1:-1],CR_title]
jira_cr_cloned_dict[jira_link]=CR_list

当我运行 send_mail_cloned() 函数时,出现了一些错误,比如:

File "/usr/lib/python2.6/email/mime/text.py", line 30, in __init__
    self.set_payload(_text, _charset)
  File "/usr/lib/python2.6/email/message.py", line 224, in set_payload
    self.set_charset(charset)
  File "/usr/lib/python2.6/email/message.py", line 266, in set_charset
    self._payload = charset.body_encode(self._payload)
  File "/usr/lib/python2.6/email/charset.py", line 387, in body_encode
    return email.base64mime.body_encode(s)
  File "/usr/lib/python2.6/email/base64mime.py", line 147, in encode
    enc = b2a_base64(s[i:i + max_unencoded])

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 54: ordinal not in range(128)

我尝试不对字符串进行编码或解码。但是,这样的话,打印 %s 本身就失败了。

有人能帮我找出在发送邮件时出现的错误吗?

1 个回答

0

我猜你的主要问题出在下面这一行:

CR_title=value[1].decode('utf-8')

你把值明确地解码成了一个Unicode字符串。然后你把它和字节字符串连接在一起,这样就隐式地把整个text当成了一个Unicode字符串。我不太确定,但我猜MIMEText可能只处理字节字符串,而不是Unicode字符串。当它试图构建消息时,就会触发一个隐式的编码过程,把内容转换成字节,而这个过程默认使用ASCII编码。

试着在把内容传给MIMEText之前,明确地把整个文本编码成UTF-8:

HTML_BODY = MIMEText(text.encode("utf-8"), 'html','utf-8')

撰写回答