用python发送html电子邮件

时间:2013-11-23 14:26:59

标签: html email python-3.x

我尝试使用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

我该如何解决这个问题? 感谢。

1 个答案:

答案 0 :(得分:2)

  

NameError:未定义名称“SMTPException”

这是因为在您当前的上下文中,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())