1

我正在努力弄清楚下面的代码出了什么问题。我正在尝试发送 html 邮件。

NOW = datetime.datetime.now()

 def sendEmail(msg):
    global NOW
    global SENDER
    global EMAILTARGET
    today = "%s/%s/%s" % (NOW.month,NOW.day,NOW.year)
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "SAR Data Report - %s" % today
    msg['From'] = SENDER
    msg['To'] = EMAILTARGET
    chunk = MIMEText(msg, 'html')
    msg.attach(chunk)
    s = smtplib.SMTP('localhost')
    s.sendmail(SENDER, EMAILTARGET, msg.as_string())
    s.quit()

上面的代码给了我以下错误:

Traceback (most recent call last):
 File "./html_mail.py", line 295, in <module>
 sendEmail(html)
 File "./html_mail.py", line 245, in sendEmail
 chunk = MIMEText(msg, 'html')
 File "/usr/lib/python2.7/email/mime/text.py", line 30, in __init__
  self.set_payload(_text, _charset)
 File "/usr/lib/python2.7/email/message.py", line 226, in set_payload
  self.set_charset(charset)
 File "/usr/lib/python2.7/email/message.py", line 268, in set_charset
  cte(self)
 File "/usr/lib/python2.7/email/encoders.py", line 73, in encode_7or8bit
  orig.encode('ascii')
  AttributeError: MIMEMultipart instance has no attribute 'encode'
4

2 回答 2

4

您的代码中的错误是您已将msg用作函数的参数,并且它与您的 MIME 消息容器(均名为msg)发生冲突。

您需要做的是将参数的名称更改为其他名称,例如html

def sendEmail(html):
...
chunk = MIMEText(html, 'html')
...
于 2012-09-20T23:34:30.340 回答
0

您将msg作为MIMEMultipart对象的 传递给MIMEText需要一个字符串的初始化程序。您应该传递一个包含要附加的 HTML 的字符串,而不是您尝试附加的消息。

于 2012-09-20T23:20:50.070 回答