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.
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.
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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With