Django EmailMultiAlternatives with Embadded Image in HTML

I am trying to send email using HTML and embadded image. Email sending works fine and also attaches the image via email, but does not show the image in HTML (inline). I used Content: ID in the view and cid in the template, but without success :( I study so many forms and apply solutions, but help in vain !. Here is my code:

html_content = render_to_string('newsletters/newsletter_template.html', vars) text_content = strip_tags(html_content) to = ' myemail@gmail.com ' msg = EmailMultiAlternatives(self.subject, text_content, settings.STAFF_FROM_EMAIL, [to]) msg.attach_alternative(html_content, "text/html") image_file = open('../media/images/banner_admin.gif', 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<image1>') msg.attach(msg_image) msg.send() 

Template File:

 <div style="border:2px solid #CCCCCC; width:900px; font-size:10px; padding:5px;"> <div style="margin-bottom: 10px;"><img src="cid:image1" /></div> <div style="">{{body|linebreaks}}</div> </div> 

Please let me know if I'm missing something here ...

+4
source share
2 answers

To insert a PNG file into email, try this code:

 for f in ['img1.png', 'img2.png']: fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img)`enter code here` msg.send() 

Now you can use <img src="cid:img1.png"> in your template. The result should be that the email client displays the image embedded in the email at the location of the <img> , and not as an attachment.

0
source

Images in HTML emails must have absolute URLs:

 <img alt="Django" src="https://www.djangoproject.com/m/img/site/hdr_logo.gif"> 
-1
source

All Articles