2013-11-23 78 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