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

How to send HTML emails with images using python3 and email library?

我想创建脚本来自动向用户列表发送“生日快乐”电子邮件。我从电子邮件库文档 examples:

中获取了此功能
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)

但是邮件客户端无法加载图片(在 outlook 2019 和 thunderbird 上测试)。

提前致谢。

您似乎正在使用 Content-ID (CID) 嵌入图像,它对电子邮件的支持有限 (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/