Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to send HTML emails with embedded images

Tags:

How can I send HTML emails with embedded images? How the HTML should link to the images? The images should be added as MultiPart email attach?

Any example is very appreciated.

like image 892
Esteban Feldman Avatar asked Sep 24 '10 13:09

Esteban Feldman


People also ask

How do I insert an image into an HTML email template?

To attach an image, you need to have the encoding scheme of the image you want to attach. This is the base64 string of the picture. You can get this by right-clicking on the image you want to attach, copy the image address, and paste it into the HTML text. The recipient will have a preview of when they open the email.

How do I embed images in an email?

Email providers, like Gmail, allow you to drag an image from a folder and drop it into an area inside the compose box that says “attach files here”. Gmail will automatically embed the image and realign it so it's in line with the rest of the plain text.


2 Answers

I achieved what op is asking for using django's mailing system. Upsides it that it'll use django settings for mailing (including a different subsystem for testing, etc. I also use mailhogs during development). It's also quite a bit higher level:

from django.conf import settings from django.core.mail import EmailMultiAlternatives   message = EmailMultiAlternatives(     subject=subject,     body=body_text,     from_email=settings.DEFAULT_FROM_EMAIL,     to=recipients,     **kwargs ) message.mixed_subtype = 'related' message.attach_alternative(body_html, "text/html") message.attach(logo_data())  message.send(fail_silently=False) 

logo_data is a helper function that attaches the logo (the image I wanted to attach in this case):

from email.mime.image import MIMEImage  from django.contrib.staticfiles import finders   @lru_cache() def logo_data():     with open(finders.find('emails/logo.png'), 'rb') as f:         logo_data = f.read()     logo = MIMEImage(logo_data)     logo.add_header('Content-ID', '<logo>')     return logo 
like image 54
WhyNotHugo Avatar answered Sep 21 '22 17:09

WhyNotHugo


http://djangosnippets.org/snippets/285/

You have to use MultiPart and cid:. It is almost always a bad idea to send html mails with images. It gives spam points to your mail and smtp server ...

Here is better example: https://djangosnippets.org/snippets/3001/

like image 35
baklarz2048 Avatar answered Sep 22 '22 17:09

baklarz2048