Django电子邮件消息为HTML

时间:2016-04-01 08:14:52

标签: html django email django-templates

我有一个电子邮件模板,用于发送不同类型的电子邮件。我宁愿不保留多个电子邮件HTML模板,因此处理此问题的最佳方法是自定义邮件内容。像这样:

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'
    send_mail(email_subject, 'message', 'from_email', [to_list], fail_silently=False, html_message=html_message)
    return

但是,当发送电子邮件时,html代码不起作用。消息显示为完全正确,有角度的括号和全部。有没有办法让我强制它呈现为HTML标签?

3 个答案:

答案 0 :(得分:5)

使用EmailMessage可以减少麻烦:

首次导入EmailMessage

from django.core.mail import EmailMessage

然后使用此代码发送html电子邮件:

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()

答案 1 :(得分:2)

您可以使用django中的EmailMultiAlternatives功能,而不是使用发送邮件发送邮件。您的代码应该类似于下面的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.")

答案 2 :(得分:0)

解决了它。不是很优雅,但确实有效。如果有人好奇,放在电子邮件模板中的变量应该如下实现:

{{ your_variable|safe|escape }}

然后它的作品!谢谢你们!