Django email message as HTML

核能气质少年 提交于 2019-12-06 05:00:13

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 EmailMultiAlternatives

def 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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!