【问题标题】:django add html email templatedjango 添加 html 电子邮件模板
【发布时间】:2015-05-29 12:02:14
【问题描述】:

此代码来自 django_messages 应用程序。即使模板应该是 html,我仍然会在电子邮件正文中获得原始 html 代码。在这种情况下需要做些什么来发送文本版本和正常工作的 HTML 版本?

{% load i18n %}
{% load url from future %}

{% blocktrans with recipient=message.recipient sender=message.sender %}Hello {{ recipient }},

you received a private message from {{ sender }} with
the following contents:{% endblocktrans %}

{{ message.body|safe }}

--
{% blocktrans %}Sent from {{ site_url }}{% endblocktrans %}

上面是new_message.html文件

下面是发送邮件的实际代码

def new_message_email(sender, instance, signal, 
    subject_prefix=_(u'New Message: %(subject)s'),
    template_name="messages/new_message.html",
    default_protocol=None,
    *args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
    ``template_name``: the template to use
    ``subject_prefix``: prefix for the email subject.
    ``default_protocol``: default protocol in site URL passed to template
"""
if default_protocol is None:
    default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')

if 'created' in kwargs and kwargs['created']:
    try:
        current_domain = Site.objects.get_current().domain
        subject = subject_prefix % {'subject': instance.subject}
        message = render_to_string(template_name, {
            'site_url': '%s://%s' % (default_protocol, current_domain),
            'message': instance,
        })

        if instance.recipient.email != "":
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                [instance.recipient.email,])
    except Exception as e:
        #print e
        pass #fail silently

if 'created' in kwargs and kwargs['created']:
    try:
        current_domain = Site.objects.get_current().domain
        subject = subject_prefix % {'subject': instance.subject}
        message = render_to_string(template_name, {
            'site_url': '%s://%s' % (default_protocol, current_domain),
            'message': instance,
        })

        if instance.recipient.email != "":
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                [instance.recipient.email,])
    except Exception as e:
        #print e
        pass #fail silently

这是我通过以下示例尝试的新代码,但它不起作用。

if 'created' in kwargs and kwargs['created']:
    try:
        current_domain = Site.objects.get_current().domain
        subject = subject_prefix % {'subject': instance.subject}
        html_content = render_to_string(template_name, {
            'site_url': '%s://%s' % (default_protocol, current_domain),
            'message': instance,
        })

        if instance.recipient.email != "":
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL,
                [instance.recipient.email,])
            msg.attach_alternative(html_content, "text/html")
            send_mail(msg)
    except Exception as e:
        #print e
        pass #fail silently

【问题讨论】:

标签: html django email templates


【解决方案1】:

在 Django 1.7+ 中,您可以在使用 send_mail 时指定 html_message。对于不支持 html 电子邮件的客户端,仍然需要 message 参数。

对于 Django 1.6 及更早版本,请参阅sending alternative content types 的说明。您无需调用send_mail,而是构建一个电子邮件消息,设置 html 内容,然后发送它。

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

【讨论】:

  • 知道 html_message 但使用的是旧版本,然后是 1.7+。我多次查看该链接,但不确定如何在上面的特定代码中应用它。
  • 您只需将您的send_mail() 替换为文档中的示例,并根据需要调整主题、正文等。你不明白哪一部分?
  • 请查看原始问题。最后我发布了新代码。
  • 它在什么方面不起作用?在编写代码时删除 try except 块,以便您可以看到问题所在,而不是静默失败。
  • 这是我得到的:send_mail() 至少需要 4 个参数(1 个给定)
猜你喜欢
  • 2014-01-16
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2010-12-20
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多