如何使用python3和电子邮件库发送带有图像的HTML电子邮件



我想创建一个脚本来自动发送"生日快乐"给用户列表的电子邮件。我从电子邮件库文档中获得了这个函数示例:

def send_email(name):
msg = EmailMessage()
msg.set_content(f"""
Dear colleagues!
Today is birthday of {name}. 
""")
balloons = make_msgid()
msg.add_alternative("""
<html>
<head></head>
<body>
<img src="cid:{balloons}" />
<h3>Dear colleagues!</h3>
<p>Today is <b>birthday</b> of {name}!</p>
<p>-- Colleagues.</p>
</body>
</html>
""".format(name=fixed_name, balloons=balloons[1:-1]), subtype='html')
with open("bday_balloons.png", 'rb') as img:
#msg.add_related(img.read(), 'image', 'png', cid=balloons)
msg.add_alternative(img.read(), 'image', 'png', cid=balloons)
msg['From'] = Address("Notification", "info", "rtdprk.ru")
msg['To'] = receiver_email
msg['Subject'] = "Birthday of {}".format(fixed_name)
with smtplib.SMTP(smtp_server) as s:
s.send_message(msg)

但图片并没有加载到邮件客户端(在outlook2019和thunderbird上进行了测试(。

提前谢谢。

看起来您正在使用内容ID(CID(嵌入图像,该ID对电子邮件的支持有限(https://www.caniemail.com/features/image-base64/)。你能使用HTML img标签,即<img src="https://www.image.com/host-somewhere-on-internet" />吗?

请参阅https://sendgrid.com/blog/embedding-images-emails-facts/了解更多信息。

最新更新