Django电子邮件为HTML

Bob*_*Bob 2 html email django 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
Run Code Online (Sandbox Code Playgroud)

但是,发送电子邮件时,html代码不起作用。该消息将按原样显示,并带有尖括号和所有内容。有没有办法强制我将其呈现为HTML标签?

Ale*_*lig 6

使用EmailMessage可以减少麻烦:

首次导入EmailMessage

from django.core.mail import EmailMessage
Run Code Online (Sandbox Code Playgroud)

然后使用此代码发送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()
Run Code Online (Sandbox Code Playgroud)


Bob*_*Bob 4

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

{{ your_variable|safe|escape }}
Run Code Online (Sandbox Code Playgroud)

然后就可以了!多谢你们!