2012-09-20 62 views
1

我在努力弄清楚下面的代碼出了什麼問題。 我正在嘗試發送html郵件。python html mail failure

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

在你的代碼中的錯誤是,你使用味精作爲在參數給你的函數,並將其與MIME消息容器(並重命名爲味精)碰撞。

你需要做的是改變的參數別的東西的名稱,如HTML

def sendEmail(html): 
... 
chunk = MIMEText(html, 'html') 
... 
+0

如果你想避免所有與SMTP的麻煩,我會建議的電子郵件傳送服務,如[AlphaMail](http://comfirm.se)或[SendGrid](http://sendgrid.com)。 –

0

你傳遞msg,這是一個MIMEMultipart對象,到MIMEText初始化,它需要一個字符串。您應該傳遞一個包含您要附加​​的HTML的字符串,而不是您要附加到的消息。