Search code examples
pythonpython-2.7html-emailemail-attachments

How to embed a linked image into a python email


There are plenty of answers on how to embed images into emails in python. What I can't figure out is how to embed an image that's clickable and leads you to a site.

Sending Multipart html emails which contain embedded images I pretty much followed the first comment of this exactly. I just need to figure out how to add a link to that image

this is what I followed

msgRoot = MIMEMultipart('related')

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

msgImage = MIMEImage(fp.read())

fp.close()

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

msgRoot.attach(msgImage)

Obviously this just embeds an image, but I need it to embed a linked image!


Solution

  • The example you linked were properly formatted HTML Emails where add_alternative() was used to supply the HTML portion of the email. You excluded this in what you've written. If you include an actual HTML body for your email, then all you need to do is wrap the image in an anchor(link) element with the url you're trying to link to.

    (Adapted from your linked question)

    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')
    

    Edit

    Don't have Python 2 around to test, but the following code from the Accepted Answer on that same thread (which was indicated as being Python 2.x compatible) presumably should work.

    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)
    

    Again, the point here being that you embed the image via html, which also allows you apply anchor tags (and basically any other styling you would like).