0

请在下面找到相关的代码片段:

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+=”””&lt;/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 会自行失败。

有人可以在发送电子邮件时帮我找出这里的错误吗?

4

1 回答 1

0

我的猜测是您的基本问题在以下行:

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

您正在将您的值显式解码为 Unicode 字符串。通过将它与字节字符串连接,您可以将整个字符串隐式创建text为 Unicode 字符串,我不确定,但我猜这MIMEText不是为了处理 Unicode 字符串而编写的,而只是为了处理字节字符串,然后,当它尝试要构造消息,它会触发隐式编码为默认使用 ASCII 的字节。

在将整个文本传递给之前尝试将整个文本显式编码为 UTF-8 MIMEText

HTML_BODY = MIMEText(text.encode("utf-8"), 'html','utf-8')
于 2013-03-19T00:13:19.023 回答