繁体   English   中英

如何在Python中使用smtplib通过电子邮件发送.html文件

[英]How to email a .html file using smtplib in Python

我一直在使用Jupyter制作html报告,我希望能够使用smtplib通过电子邮件发送这些报告。 我已经能够成功发送电子邮件,但无法获取HTML报告以附加到或嵌入电子邮件中。

我一直在使用的代码如下所示:

fromaddr = "myemail@domain.com.au"
toaddr = "myfriendsemail@domain.com.au"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Automatic Weekly Report"

html = open("WeeklyReport.html")
part2 = MIMEText(html.read(), 'text/html')
msg.attach(part2)

server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login("myemail@domain.com.au", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

我认为问题主要出在我从https://docs.python.org/3.4/library/email-examples.html修改而来的中间部分

html = open("WeeklyPnlReport.html")
part2 = MIMEText(html.read(), 'text/html')
msg.attach(part2)

运行此代码时,我收到一封电子邮件,该邮件在Gmail中打开,为空白,附件为“ noname”。 预览它不起作用,下载它导致我的电脑不知道打开哪个文件。

如果我将中间位更改为:

part2 = MIMEText(html.read(), 'html')

我收到一封电子邮件,上面写着“邮件已裁剪”,然后当我单击“查看整个邮件”时,会弹出一个新标签,其中包含报告的html文本。

如果我运行:

part2 = MIMEText(html, 'html')

我收到一个错误“'_io.TextIOWrapper'对象没有属性'encode'”。

我目前对要做的事情很迷茫。 我基本上只希望将html报告附加到我的电子邮件中或包含在电子邮件中。 我看过MIMEText的文档,但是它相当稀疏,而且比我头上的还大。 我想知道更多有关它如何运行的信息,但更具体地说,是如何使html文件嵌入电子邮件或附加到电子邮件中。

提前致谢。

不指定主要内容类型,仅指定次要类型:不是text/html ,而是html

part2 = MIMEText(html.read(), 'html')  # Note: no "text/"

除非要发送多个部分,否则不需要multipart消息。

如果您确实使用multipart ,请指定次要内容类型。 默认的多部分类型是multipart/mixed 您可能需要multipart/alternative

msg = MIMEMultipart('alternative')

这可能对您有用:

from email.mime.text import MIMEText
import smtplib


fromaddr = "me@example.com"
toaddr = "myfriend@example.com"


html = open("WeeklyReport.html")
msg = MIMEText(html.read(), 'html')
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Automatic Weekly Report"

debug = False
if debug:
    print(msg.as_string())
else:
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.login("me@example.com", "password")
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

暂无
暂无

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

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