How to send html email with django with dynamic content in it?


Question

Can anyone please help me sending html email with dynamic contents. One way is to copy the entire html code into a variable and populate the dynamic code within it in Django views, but that does not seem to be a good idea, as its a very large html file.

I would appreciate any suggestions.

Thanks.

1
30
6/9/2010 10:47:55 AM

Example:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject, from_email, to = 'Subject', 'from@xxx.com', 'to@xxx.com'

html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value
text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least.

# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

Reference

http://www.djangofoo.com/250/sending-html-email/comment-page-1#comment-11401

46
1/16/2018 4:13:30 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon