Sending images in django emails

Sending images in django emails

  • Images have proven to be one of the most compelling and information-dense media available to marketers today. A good image can communicate emotion, transmit knowledge and get that critical engagement leading to a purchase.

  • Every marketer needs to consider including images across their media, and email is no different. There is, however, a big caveat for images in email: They can be notoriously difficult to work with.

  • If not handled well, embedding images in an email can affect deliverability, engagement and sender reputation. Appearances in a recipient’s inbox also can change from email client to email client.

  • To get around these issues, it’s critical to understand the usable methods for embedding images in emails, as well as their benefits and drawbacks.

  • Senders today primarily have three different methods for embedding images at their disposal: CID tags, inline embedding and linked images. But before using these methods, email marketers should take a close look at how their active recipients behave with current emails.

  • The importance of analyzing recipient behavior before using images cannot be overstated. You will need to know what email clients to design images for, what size is optimal for these email clients, how these clients treat ALT text and how they both do and do not render images for recipients.

  • We can embed images in two ways 1. by using content id and 2. by using web image url.

Let's send images in django email.

from email.mime.image import MIMEImage
from django.core.mail import EmailMultiAlternatives

subject = 'Django sending email'
body_html = '''
<html>
    <body>
        <img src="cid:logo.png" />
        <img src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" />
    </body>
</html>
'''

from_email = '[email protected]'
to_email = '[email protected]'

msg = EmailMultiAlternatives(
    subject,
    body_html,
    from_email=from_email,
    to=[to_email]
)

msg.mixed_subtype = 'related'
msg.attach_alternative(body_html, "text/html")
img_dir = 'static'
image = 'logo.png
file_path = os.path.join(img_dir, image)
with open(file_path, 'r') as f:
    img = MIMEImage(f.read())
    img.add_header('Content-ID', '<{name}>'.format(name=image))
    img.add_header('Content-Disposition', 'inline', filename=image)
msg.attach(img)

Like above we can send embed and send the images in the django. In the above code we are using the cid for the first email and web url for the second email. It's that simple to send images in the emails.