简体   繁体   English

使用python发送HTML电子邮件

[英]Send html email with python

I tried to send a email with html text using python. 我试图使用python发送带有html文本的电子邮件。

The html text is loaded from a html file: html文本是从html文件加载的:

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

And after, I send the email: 之后,我发送电子邮件:

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")

I got this error: 我收到此错误:

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

How can I solve this problem? 我怎么解决这个问题? Thanks. 谢谢。

NameError: name 'SMTPException' is not defined NameError:名称“ SMTPException”未定义

This is because in your current context, SMTPException doesn't stand for anything. 这是因为在您当前的上下文中,SMTPException并不代表任何东西。

You'll need to do: 您需要执行以下操作:

except smtplib.SMTPException:

Also, note that building the headers by hand is a bad idea. 另外,请注意,手动构建标头不是一个好主意。 Can't you use inbuilt modules? 您不能使用内置模块吗?

The below is a copy-paste of relevant parts from one of my projects. 以下是我其中一个项目的相关部分的复制粘贴。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM