百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

django-templated-email

> 编程语言
开源

Django 模块可使用 Django 模板或事务性邮件提供商(如 Mailchimp、Silverpop 等)轻松发送带有模板的邮件

784 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

Django 模块可使用 Django 模板或事务性邮件提供商(如 Mailchimp、Silverpop 等)轻松发送带有模板的邮件

============================== Django-Templated-Email

|GitterBadge|_ |PypiversionBadge|_ |PythonVersionsBadge|_ |LicenseBadge|_

:Info: A Django oriented templated email sending class :Original Author: Bradley Whittington (http://github.com/bradwhittington, http://twitter.com/darb) :Maintained by: Vinta Software: https://www.vinta.com.br/ :Tests: |GABadge|_ |CoverageBadge|_

Overview

django-templated-email is oriented towards sending templated emails. The library supports template inheritance, adding cc'd and bcc'd recipients, configurable template naming and location.

The send_templated_email method can be thought of as the render_to_response shortcut for email.

Make sure you are reading the correct documentation:

develop branch: https://github.com/vintasoftware/django-templated-email/blob/develop/README.rst

stable pypi/main: https://github.com/vintasoftware/django-templated-email/blob/main/README.rst

Requirements

  • Python (3.9*, 3.10, 3.11, 3.12, 3.13)
  • Django (4.2, 5.0, 5.1)

We highly recommend and only officially support the latest patch release of each Python and Django series.

Python 3.9 is no longer supported in Django 5.0 and newer, so is only supported with Django 4.2.

Getting going - installation

Installing::

pip install django-templated-email

You can add the following to your settings.py (but it works out the box):

.. code-block:: python

TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend'

# You can use a shortcut version
TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django'

# You can also use a class directly
from templated_email.backends.vanilla_django import TemplateBackend
TEMPLATED_EMAIL_BACKEND = TemplateBackend

Sending templated emails

Example usage using vanilla_django TemplateBackend backend

Python to send mail:

.. code-block:: python

from templated_email import send_templated_mail
send_templated_mail(
        template_name='welcome',
        from_email='[email protected]',
        recipient_list=['[email protected]'],
        context={
            'username':request.user.username,
            'full_name':request.user.get_full_name(),
            'signup_date':request.user.date_joined
        },
        # Optional:
        # cc=['[email protected]'],
        # bcc=['[email protected]'],
        # headers={'My-Custom-Header':'Custom Value'},
        # template_prefix="my_emails/",
        # template_suffix="email",
)

If you would like finer control on sending the email, you can use get_templated_email, which will return a django EmailMessage object, prepared using the vanilla_django backend:

.. code-block:: python

from templated_email import get_templated_mail
get_templated_mail(
        template_name='welcome',
        from_email='[email protected]',
        to=['[email protected]'],
        context={
            'username':request.user.username,
            'full_name':request.user.get_full_name(),
            'signup_date':request.user.date_joined
        },
        # Optional:
        # cc=['[email protected]'],
        # bcc=['[email protected]'],
        # headers={'My-Custom-Header':'Custom Value'},
        # template_prefix="my_emails/",
        # template_suffix="email",
)

You can also cc and bcc recipients using cc=['[email protected]'].

Your template

The templated_email/ directory needs to be the templates directory.

The backend will look in my_app/templates/templated_email/welcome.email :

.. code-block:: python

{% block subject %}My subject for {{username}}{% endblock %}
{% block plain %}
  Hi {{full_name}},

  You just signed up for my website, using:
      username: {{username}}
      join date: {{signup_date}}

  Thanks, you rock!
{% endblock %}

If you want to include an HTML part to your emails, simply use the 'html' block :

.. code-block:: python

{% block html %}

Hi {{full_name}},

You just signed up for my website, using:

        username{{username}}
        join date{{signup_date}}

Thanks, you rock!

{% endblock %}

The plain part can also be calculated from the HTML using html2text . If you don't specify the plain block and html2text package is installed, the plain part will be calculated from the HTML part. You can disable this behaviour in settings.py :

.. code-block:: python

TEMPLATED_EMAIL_AUTO_PLAIN = False

You can also specify a custom function that converts from HTML to the plain part :

.. code-block:: python

def convert_html_to_text(html):
    ...

TEMPLATED_EMAIL_PLAIN_FUNCTION = convert_html_to_text

You can globally override the template dir, and file extension using the following variables in settings.py :

.. code-block:: python

TEMPLATED_EMAIL_TEMPLATE_DIR = 'templated_email/' #use '' for top level template dir, ensure there is a trailing slash
TEMPLATED_EMAIL_FILE_EXTENSION = 'email'

You can also set a value for template_prefix and template_suffix for every time you call send_templated_mail, if you wish to store a set of templates in a different directory. Remember to include a trailing slash.

Using with Django Anymail _

Anymail integrates several transactional email service providers (ESPs) into Django, with a consistent API that lets you use ESP-added features without locking your code to a particular ESP. It supports Mailgun, Postmark, SendGrid, SparkPost and more.

You can use it with django-templated-email, just follow their instructions in their quick start _ to configure it.

Optionally you can use their custom EmailMessage _ class with django-templated-email by using the following settings:

.. code-block:: python

# This replaces django.core.mail.EmailMessage
TEMPLATED_EMAIL_EMAIL_MESSAGE_CLASS='anymail.message.AnymailMessage'

# This replaces django.core.mail.EmailMultiAlternatives
TEMPLATED_EMAIL_EMAIL_MULTIALTERNATIVES_CLASS='anymail.message.AnymailMessage'

Inline images

You can add inline images to your email using the InlineImage class.

First get the image content from a file or a ImageField:

.. code-block:: python

# From a file
with open('pikachu.png', 'rb') as pikachu:
  image = pikachu.read()

# From an ImageField
# Suppose we have this model
class Company(models.Model):
  logo = models.ImageField()

image = company.logo.read()

Then create an instance of InlineImage:

.. code-block:: python

from templated_email import InlineImage

inline_image = InlineImage(filename="pikachu.png", content=image)

Now pass the object on the context to the template when you send the email.

.. code-block:: python

send_templated_mail(template_name='welcome',
                    from_email='[email protected]',
                    recipient_list=['[email protected]'],
                    context={'pikachu_image': inline_image})

Finally in your template add the image on the html template block:

.. code-block:: html

Note: All InlineImage objects you add to the context will be attached to the e-mail, even if they are not used in the template.

Add link to view the email on the web

.. code-block:: python

# Add templated email to INSTALLED_APPS
INSTALLED_APPS = [
  ...
  'templated_email'
]

.. code-block:: python

# and this to your url patterns
url(r'^', include('templated_email.urls', namespace='templated_email')),

.. code-block:: python

# when sending the email use the *create_link* parameter.
send_templated_mail(
    template_name='welcome', from_email='[email protected]',
    recipient_list=['[email protected]'],
    context={}, create_link=True)

And, finally add the link to your template.

.. code-block:: html

{% if email_uuid %}
  
  You can view this e-mail on the web here:
  
    here
  
{% endif %}

Notes:

  • A copy of the rendered e-mail will be stored on the database. This can grow if you send too many e-mails. You are responsible for managing it.
  • If you use InlineImage all images will be uploaded to your media storage, keep that in mind too.

Class Based Views

It's pretty common for emails to be sent after a form is submitted. We include a mixin to be used with any view that inherit from Django's FormMixin.

In your view add the mixin and the usual Django's attributes:

.. code-block:: python

from templated_email.generic_views import TemplatedEmailFormViewMixin

class AuthorCreateView(TemplatedEmailFormViewMixin, CreateView):
    model = Author
    fields = ['name', 'email']
    success_url = '/create_author/'
    template_name = 'authors/create_author.html'

By default the template will have the form_data if the form is valid or from_errors if the form is not valid in it's context.

You can view an example here _

Now you can use the following attributes/methods to customize it's behavior:

Attributes:

templated_email_template_name (mandatory if you don't implement templated_email_get_template_names()): String naming the template you want to use for the email. ie: templated_email_template_name = 'welcome'.

templated_email_send_on_success (default: True): This attribute tells django-templated-email to send an email if the form is valid.

templated_email_send_on_failure (default: False): This attribute tells django-templated-email to send an email if the form is invalid.

templated_email_from_email (default: settings.TEMPLATED_EMAIL_FROM_EMAIL. If it's also not defined, falls back to DEFAULT_FROM_EMAIL): String containing the email to send the email from.

Methods:

templated_email_get_template_names(self, valid) (mandatory if you don't set templated_email_template_name): If the method returns a string it will use it as the template to render the email. If it returns a list it will send the email only with the first existing template.

templated_email_get_recipients(self, form) (mandatory): Return the recipient list to whom the email will be sent to. ie:

.. code-block:: python

  def templated_email_get_recipients(self, form):
      return [form.data['email']]

**templated_email_get_context_data(kwargs) (optional): Use this method to add extra data to the context used for rendering the template. You should get the parent class's context from calling super. ie:

.. code-block:: python

  def templated_email_get_context_data(self, **kwargs):
      context = super(ThisClassView, self).templated_email_get_context_data(**kwargs)
      # add things to context
      return context

templated_email_get_send_email_kwargs(self, valid, form) (optional): Add or change the kwargs that will be used to send the e-mail. You should call super to get the default kwargs. ie:

.. code-block:: python

def templated_email_get_send_email_kwargs(valid, form):
  kwargs = super(ThisClassView, self).templated_email_get_send_email_kwargs(valid, form)
  kwargs['bcc'] = ['[email protected]']
  return kwargs

**templated_email_send_templated_mail(*args, kwargs) (optional): This method calls django-templated-email's send_templated_mail method. You could change this method to use a celery's task for example or to handle errors.

Settings

You can configure Django-Templated-Email by setting the following settings

.. code-block:: python

TEMPLATED_EMAIL_FROM_EMA

Issues· 6 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Python

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言