-1
from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

I want to be able to sends newsletters or emails that have been designed properly, including images if possible. I was wondering if I could change this

html_content = '<p>This is an <strong>important</strong> message.</p>'

into an html template file. Like this

html_content = 'newsletter/news.html'

If not then how do I go about sending emails like that of Quora and other websites.`

sambeth
  • 1,550
  • 2
  • 10
  • 18
  • Possible duplicate of [Creating email templates with Django](http://stackoverflow.com/questions/2809547/creating-email-templates-with-django) – Sayse Jan 31 '17 at 11:41

2 Answers2

2

You can easily take any template and turn it into a string, for any purpose including sending mails:

from django.template.loader import get_template

template = get_template('newsletter/news.html')
html_content = template.render({pass any context you might need})
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
2

You can't directly pass a template like that but you can use render_to_string

from django.template.loader import render_to_string
html_content  = render_to_string('newsletter/news.html', {'foo': 'bar'})

However be aware that there are certain limitations in HTML email. For example you can't use javascript. Images may or may not be displayed and external stylesheets cannot be used either.

e4c5
  • 52,766
  • 11
  • 101
  • 134