django - django 中的电子邮件模板

标签 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,])

我认为这有一个缺陷:要编辑电子邮件的主题和内容,您必须同时编辑 View 和模板。虽然我可以证明授予管理员用户访问模板的权限,但我不会授予他们访问原始 python 的权限!

如果您可以在电子邮件中指定 block 并在发送电子邮件时将它们单独拉出,那就太酷了:

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

但是你会怎么做呢?您将如何一次只渲染一个 block ?

最佳答案

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

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

我已经重构为默认通过列表迭代电子邮件发送,并且有一些实用方法可以发送到单个电子邮件和django.contrib.auth User (单个和多个)。我所涵盖的内容可能超出了我实际需要的范围,但是就这样吧。

我也可能对 Python 的热爱有些过头了。

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)

一如既往,如果您可以改进这一点,请这样做。

关于django - django 中的电子邮件模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051526/

相关文章:

asp.net - 使用远程浏览器的 ASP.NET 应用程序中的 SmtpException

django templates Unclosed tag on line 10 : 'if' . 寻找其中之一:endif

python - 命名 Python 记录器

python - 想要在 django 应用程序上运行 python 脚本

python - 基准测试 Django 应用程序

php - 当域由 Media Temple 托管且电子邮件由 domains.live.com 托管时,使用 PHP 发送电子邮件

python - 为什么 django 的 create_user 方法不验证唯一性?

php - 如何调试laravel mailgun

python - 如何查看生成到 django 模板变量中的异常?

html - Django:使用静态的、困难的时间和路径来渲染 css