Django email message as HTML Django email message as HTML django django

Django email message as HTML


Use EmailMessage to do it with less trouble:

First import EmailMessage:

from django.core.mail import EmailMessage

Then use this code to send html email:

email_body = """\    <html>      <head></head>      <body>        <h2>%s</h2>        <p>%s</p>        <h5>%s</h5>      </body>    </html>    """ % (user, message, email)email = EmailMessage('A new mail!', email_body, to=['someEmail@gmail.com'])email.content_subtype = "html" # this is the crucial part email.send()


You can use EmailMultiAlternatives feature present in django instead of sending mail using send mail. Your code should look like the below snipet.

from django.core.mail import EmailMultiAlternativesdef email_form(request):    html_message = loader.render_to_string(            'register/email-template.html',            {                'hero': 'email_hero.png',                'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">meow@something.com</a>',                'from_email': 'lala@lala.com',            }        )    email_subject = 'Thank you for your beeswax!'    to_list = 'johndoe@whatever.com'    mail = EmailMultiAlternatives(            email_subject, 'This is message', 'from_email',  [to_list])    mail.attach_alternative(html_message, "text/html")    try:        mail.send()    except:        logger.error("Unable to send mail.")


Solved it. Not very elegant, but it does work. In case anyone's curious, the variable placed in the email template should be implemented as so:

{{ your_variable|safe|escape }}

Then it works! Thanks guys!