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

时间:2020-12-24 15:46:39

标签: python html-email

我想创建脚本以自动向用户列表发送“生日快乐”电子邮件。我从电子邮件库文档 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 上测试)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您似乎是使用 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/