django中的电子邮件模板

时间:2010-01-12 18:54:45

标签: django email django-templates django-email

众所周知(或应该),您可以使用Django的模板系统来呈现电子邮件正文:

def email(email, subject, template, context):
    from django.core.mail import send_mail
    from django.template import loader, Context

    send_mail(subject, loader.get_template(template).render(Context(context)), 'from@domain.com', [email,])

这有一个缺陷:要编辑电子邮件的主题和内容,您必须同时编辑视图和模板。虽然我可以证明给管理员用户访问模板是合理的,但我没有让他们访问原始python!

如果您可以在电子邮件中指定块并在发送电子邮件时单独将其拉出来,那真的很酷:

{% block subject %}This is my subject{% endblock %}
{% block plaintext %}My body{% endblock%}
{% block html %}My HTML body{% endblock%}

但是你会怎么做?你会如何一次只渲染一个块?

3 个答案:

答案 0 :(得分:11)

这是我的第三次迭代工作。它假设你有一个像这样的电子邮件模板:

{% block subject %}{% endblock %}
{% block plain %}{% endblock %}
{% block html %}{% endblock %}

我已经重构了默认情况下迭代通过列表发送的电子邮件,并且有一些实用程序方法可以发送到单个电子邮件和django.contrib.auth User s(单个和多个)。我覆盖的可能比我明智的需要还要多,但你去了。

我也可能已经超越了Python-love。

def email_list(to_list, template_path, context_dict):
    from django.core.mail import send_mail
    from django.template import loader, Context

    nodes = dict((n.name, n) for n in loader.get_template(template_path).nodelist if n.__class__.__name__ == 'BlockNode')
    con = Context(context_dict)
    r = lambda n: nodes[n].render(con)

    for address in to_list:
        send_mail(r('subject'), r('plain'), 'from@domain.com', [address,])

def email(to, template_path, context_dict):
    return email_list([to,], template_path, context_dict)

def email_user(user, template_path, context_dict):
    return email_list([user.email,], template_path, context_dict)

def email_users(user_list, template_path, context_dict):
    return email_list([user.email for user in user_list], template_path, context_dict)

与以往一样,如果你可以改进,请做。

答案 1 :(得分:0)

只需使用两个模板:一个用于正文,另一个用于主题。

答案 2 :(得分:0)

我无法使用{% body %}标签获取模板继承,所以我切换到这样的模板:

{% extends "base.txt" %}

{% if subject %}Subject{% endif %}
{% if body %}Email body{% endif %}
{% if html %}<p>HTML body</p>{% endif %}

现在我们必须渲染模板三次,但继承可以正常工作。

c = Context(context, autoescape = False)
subject = render_to_string(template_name, {'subject': True}, c).strip()
body = render_to_string(template_name, {'body': True}, c).strip()
c = Context(context, autoescape = True)
html = render_to_string(template_name, {'html': True}, c).strip()

我还发现在渲染非HTML文本时必须关闭自动窗口以避免电子邮件中的转义文本