I am trying to send an HTML email that would render an inline image. My code in views.py is as follows:
import ...
def signup_mail_function(form): # here, form is just my context
subject = "Signup Successful"
html_message = render_to_string('emailTemplate.html', {'form': form})
plain_message = strip_tags(html_message)
from_email = 'uconnect786@gmail.com'
to_email = [form.email]
# Sending email here
msg = EmailMultiAlternatives(subject=subject, body=plain_message, from_email=from_email,to=to_email)
msg.attach_alternative(html_message, "text/html")
msg.content_subtype = 'html'
msg.mixed_subtype = 'related'
img_path = settings.STATIC_DIR + '/images/blogsImage.svg' # path of my image
image_name = Path(img_path).name # Testing image name,which returns out to be same as image name i.e blogsImage.svg
print(img_path, image_name) # testing image paths here
with open(img_path, 'rb') as f:
image = MIMEImage(f.read(), _subtype="svg+xml")
msg.attach(image)
image.add_header('Content-ID', "<{}>".format(image_name)) # Setting content ID
print("<{}>".format(image_name)) # Testing content ID
msg.send()
So the above is my handling code of email message. In the template, I am doing the following:
<img alt="Blog Image" src="cid:blogsImage.svg" />
Email is sent successfully with the image as the attachment but actually I was expecting to get the image as an inline image within the Html page.
The email I received, You see no images are displayed within Html template so 'alt' tags of those images pop up
I could snapshot the whole Html page but below it, I have that image as an attachment.
Tried:
I also tried to test image insertion within my Html template using direct URLs like the following:
<img src="https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=.........." alt="Image">
But that didn't work out either. I have almost read every article and blog about rendering inline images with Django, stack overflow questions and answers but none of them has worked for me although I am coding the same way. Kindly someone point me in the right direction here!