【问题标题】:How to embed a linked image into a python email如何将链接图像嵌入到 python 电子邮件中
【发布时间】:2019-05-08 11:38:35
【问题描述】:

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

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

这是我关注的

msgRoot = MIMEMultipart('related')

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

msgImage = MIMEImage(fp.read())

fp.close()

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

msgRoot.attach(msgImage)

显然这只是嵌入图像,但我需要它来嵌入链接图像!

【问题讨论】:

    标签: python python-2.7 html-email email-attachments


    【解决方案1】:

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

    (改编自您的链接问题)

    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 嵌入图像,这还允许您应用锚标签(以及基本上任何其他您想要的样式)。

    【讨论】:

    • 这适用于 python 3,有什么适用于 python 2 的吗?
    • 使用来自其他答案的 Python 2.x 代码进行了更新
    猜你喜欢
    • 2011-01-26
    • 2022-09-25
    • 2012-03-30
    • 2011-10-30
    • 2014-10-03
    • 1970-01-01
    • 2021-12-23
    • 2017-11-05
    • 2018-12-24
    相关资源
    最近更新 更多