如何将链接图像嵌入 python 电子邮件

How to embed a linked image into a python email

python 中有很多关于如何将图像嵌入电子邮件的答案。我想不通的是如何嵌入一张可点击并引导您访问网站的图片。

Sending Multipart html emails which contain embedded images 我几乎完全遵循了第一条评论。我只需要弄清楚如何向该图像添加 link

这是我关注的

msgRoot = MIMEMultipart('related')

fp = open('test.jpg', 'rb')

msgImage = MIMEImage(fp.read())

fp.close()

msgImage.add_header('Content-ID', "<image1>")

msgRoot.attach(msgImage)

显然这只是嵌入了一张图片,但我需要它来嵌入一张 linked 图片!

您 link 编辑的示例格式正确 HTML 电子邮件,其中 add_alternative() 用于提供电子邮件的 HTML 部分。您在所写内容中排除了这一点。如果您在电子邮件中包含一个实际的 HTML 正文,那么您需要做的就是将图像包装在一个锚点 (link) 元素中,并带有您要 url 31=]到.

(改编自您的 linked 问题)

msg.add_alternative("""\
<html>
    <body>
        <p>Click the Image below to visit our site!</p>
        <a href="www.google.com"><img src="cid:{image_cid}"></a>
    </body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')

编辑

没有 Python 2 可以测试,但来自同一线程上的已接受答案的以下代码(表明与 Python 2.x 兼容)大概应该可以。

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><a href="www.google.com"><img src="cid:image1"></a><br>Nifty!', 'html')
msgAlternative.attach(msgText)

同样,这里的要点是您通过 html 嵌入图像,这也允许您应用锚标记(以及基本上您想要的任何其他样式)。