我目前正在使用以下代码每天向用户发送3次电子邮件(其中包含报告)。我想在此电子邮件中添加图表,但似乎无法弄清楚如何。
def HTML_Email(subject, to, html, files, filename):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application
# Create message container - the correct MIME type is
multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = "ChicagoGISScripts@mobilitie.com"
msg['To'] = ", ".join(to)
# Record the MIME types of both parts - text/plain and text/html
part2 = MIMEText(html, 'html')
# create PDF attachment
fp=open(files,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="xlsx")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part2)
# Send the message via local SMTP server.
user = 'ausername'
pwd = 'apassword'
s = smtplib.SMTP('smtp.office365.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(user,pwd)
s.sendmail(msg['From'], to, msg.as_string())
s.quit()
通常情况下,我会使用类似的内容来配合它,但我试图在我的计算机上包含一个本地存储的.png。是不是要将图像嵌入到电子邮件的正文中,我在这里缺少什么?
html = """\
<html>
<head></head>
<body>
<p><font face ="Gotham, monospace">Some HTML,<br><br>
<img src="C:\\Users\\Me\\Desktop\\graphs.png"></img></font>
</p>
</body>
</html>
"""
答案 0 :(得分:2)
由于您未在服务器上托管图像,因此无法使用普通链接将其嵌入电子邮件中。尝试将.png文件编码为data uri并将其设置为src
修改强>
查看this other answer以了解如何在python中执行此操作
编辑2
生成的html应如下所示
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
答案 1 :(得分:0)
正是RemedialBear所说的。您必须在服务器上托管电子邮件,并在您的电子邮件正文中包含绝对src。
而不是:
<img src="C:\\Users\\Me\\Desktop\\graphs.png">
你需要:
<img src="http://www.somedomain.com/images/graphs.png" alt="Name' />