2013-11-23 106 views
1

我試圖用python發送帶有html文本的郵件。用Python發送html郵件

HTML文本是由HTML文件中加載:

ft = open("a.html", "r", encoding = "utf-8") 
text = ft.read() 
ft.close() 

,後,我發送電子郵件:

message = "From: %s\r\nTo: %s\r\nMIME-Version: 1.0\nContent-type: text/html\r\nSubject: 
%s\r\n\r\n%s" \ 
      % (sender,receiver,subject,text) 
    try: 
     smtpObj = smtplib.SMTP('smtp.gmail.com:587') 
     smtpObj.starttls() 
     smtpObj.login(username,password) 
     smtpObj.sendmail(sender, [receiver], message) 
     print("\nSuccessfully sent email") 
    except SMTPException: 
     print("\nError unable to send email") 

我得到這個錯誤:

Traceback (most recent call last): 
    File "C:\Users\Henry\Desktop\email_prj\sendEmail.py", line 54, in <module> 
    smtpObj.sendmail(sender, [receiver] + ccn, message) 
    File "C:\Python33\lib\smtplib.py", line 745, in sendmail 
    msg = _fix_eols(msg).encode('ascii') 
    UnicodeEncodeError: 'ascii' codec can't encode character '\xe0' in position 1554: 
    ordinal not in range(128) 

    During handling of the above exception, another exception occurred: 

    Traceback (most recent call last): 
    File "C:\Users\Henry\Desktop\email_prj\sendEmail.py", line 56, in <module> 
    except SMTPException: 
    NameError: name 'SMTPException' is not defined 

哪有我解決了這個問題? 謝謝。

回答

2

NameError: name 'SMTPException' is not defined

這是因爲在您當前的上下文中,SMTPException並不代表任何東西。

你需要做的事:

except smtplib.SMTPException: 

另外,注意用手構建頭是一個壞主意。你不能使用內置模塊嗎?

以下是相關零部件的複製粘貼,來自我的其中一個項目。

from email.MIMEMultipart import MIMEMultipart 
from email.MIMEBase import MIMEBase 
from email.MIMEText import MIMEText 

.... 
.... 
.... 
msg = MIMEMultipart() 

msg['From'] = self.username 
msg['To'] = to 
msg['Subject'] = subject 

msg.attach(MIMEText(text)) 

mailServer = smtplib.SMTP("smtp.gmail.com", 587) 
mailServer.ehlo() 
mailServer.starttls() 
mailServer.ehlo() 
mailServer.login(self.username, self.password) 
mailServer.sendmail(self.username, to, msg.as_string()) 
+0

謝謝你的代碼。 – user3025003