【问题标题】:How to send HTML emails with images using python3 and email library?如何使用 python3 和电子邮件库发送带有图像的 HTML 电子邮件?
【发布时间】:2020-12-24 15:46:39
【问题描述】:

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

提前谢谢你。

【问题讨论】:

标签: python html-email


【解决方案1】:

您似乎正在使用 Content-ID (CID) 嵌入图像,它对电子邮件的支持有限 (https://www.caniemail.com/features/image-base64/)。你可以使用 HTML img 标签,即&lt;img src="https://www.image.com/host-somewhere-on-internet" /&gt;吗?

更多信息请参见https://sendgrid.com/blog/embedding-images-emails-facts/

【讨论】:

  • Gmail 和 Thunderbird 会阻止直接链接到图像,所以我不会考虑这种方式。感谢 sendgrid 文章的链接,它让我对嵌入式图像有了更好的理解。
  • 很抱歉,这是错误的(“Gmail 和 Thunderbird 阻止了指向图像的直接链接”)。使用&lt;img&gt; 标签是所有地方的标准做法。无处不在。
猜你喜欢
  • 2013-11-11
  • 2021-03-26
  • 2013-06-01
  • 1970-01-01
  • 2011-08-27
  • 2012-04-07
  • 2011-04-16
相关资源
最近更新 更多