Package: django-templated-email
Info:A Django oriented templated email sending classAuthor:Bradley Whittington (http://github.com/bradwhittington,http://twitter.com/darb)Tests:Overviewdjango-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.rststable pypi/master:https://github.com/vintasoftware/django-templated-email/blob/master/README.rstRequirementsPython (3.6, 3.7, 3.8, 3.9)Django (2.2, 3.1, 3.2)Wehighly recommendand only officially support the latest patch release of
each Python and Django series.Getting going - installationInstalling:pip install django-templated-emailYou can add the following to your settings.py (but it works out the box):TEMPLATED_EMAIL_BACKEND='templated_email.backends.vanilla_django.TemplateBackend'# You can use a shortcut versionTEMPLATED_EMAIL_BACKEND='templated_email.backends.vanilla_django'# You can also use a class directlyfromtemplated_email.backends.vanilla_djangoimportTemplateBackendTEMPLATED_EMAIL_BACKEND=TemplateBackendSending templated emailsExample usage using vanilla_django TemplateBackend backendPython to send mail:fromtemplated_emailimportsend_templated_mailsend_templated_mail(template_name='welcome',from_email='from@example.com',recipient_list=['to@example.com'],context={'username':request.user.username,'full_name':request.user.get_full_name(),'signup_date':request.user.date_joined},# Optional:# cc=['cc@example.com'],# bcc=['bcc@example.com'],# 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 useget_templated_email, which will return a djangoEmailMessageobject, prepared using thevanilla_djangobackend:fromtemplated_emailimportget_templated_mailget_templated_mail(template_name='welcome',from_email='from@example.com',to=['to@example.com'],context={'username':request.user.username,'full_name':request.user.get_full_name(),'signup_date':request.user.date_joined},# Optional:# cc=['cc@example.com'],# bcc=['bcc@example.com'],# headers={'My-Custom-Header':'Custom Value'},# template_prefix="my_emails/",# template_suffix="email",)You can alsoccandbccrecipients usingcc=[‘example@example.com’].Your templateThe templated_email/ directory needs to be the templates directory.The backend will look inmy_app/templates/templated_email/welcome.email:{%blocksubject%}Mysubjectfor{{username}}{%endblock%}{%blockplain%}Hi{{full_name}},Youjustsignedupformywebsite,using:username:{{username}}joindate:{{signup_date}}Thanks,yourock!{%endblock%}If you want to include an HTML part to your emails, simply use the ‘html’ block :{%blockhtml%}<p>Hi{{full_name}},</p><p>Youjustsignedupformywebsite,using:<dl><dt>username</dt><dd>{{username}}</dd><dt>joindate</dt><dd>{{signup_date}}</dd></dl></p><p>Thanks,yourock!</p>{%endblock%}The plain part can also be calculated from the HTML usinghtml2text. If you don’t specify the plain block andhtml2textpackage is installed, the plain part will be calculated from the HTML part. You can disable this behaviour in settings.py :TEMPLATED_EMAIL_AUTO_PLAIN=FalseYou can also specify a custom function that converts from HTML to the plain part :defconvert_html_to_text(html):...TEMPLATED_EMAIL_PLAIN_FUNCTION=convert_html_to_textYou can globally override the template dir, and file extension using the following variables in settings.py :TEMPLATED_EMAIL_TEMPLATE_DIR='templated_email/'#use '' for top level template dir, ensure there is a trailing slashTEMPLATED_EMAIL_FILE_EXTENSION='email'You can also set a value fortemplate_prefixandtemplate_suffixfor every time you callsend_templated_mail, if you wish to store a set of templates in a different directory. Remember to include a trailing slash.Using withDjango AnymailAnymail 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 theirquick startto configure it.Optionally you can use their customEmailMessageclass with django-templated-email by using the following settings:# This replaces django.core.mail.EmailMessageTEMPLATED_EMAIL_EMAIL_MESSAGE_CLASS='anymail.message.AnymailMessage'# This replaces django.core.mail.EmailMultiAlternativesTEMPLATED_EMAIL_EMAIL_MULTIALTERNATIVES_CLASS='anymail.message.AnymailMessage'Inline imagesYou can add inline images to your email using theInlineImageclass.First get the image content from a file or aImageField:# From a filewithopen('pikachu.png','rb')aspikachu:image=pikachu.read()# From an ImageField# Suppose we have this modelclassCompany(models.Model):logo=models.ImageField()image=company.logo.read()Then create an instance ofInlineImage:fromtemplated_emailimportInlineImageinline_image=InlineImage(filename="pikachu.png",content=image)Now pass the object on the context to the template when you send the email.send_templated_mail(template_name='welcome',from_email='from@example.com',recipient_list=['to@example.com'],context={'pikachu_image':inline_image})Finally in your template add the image on the html template block:<imgsrc="{{ pikachu_image }}">Note: AllInlineImageobjects 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# Add templated email to INSTALLED_APPSINSTALLED_APPS=[...'templated_email']# and this to your url patternsurl(r'^',include('templated_email.urls',namespace='templated_email')),# when sending the email use the *create_link* parameter.send_templated_mail(template_name='welcome',from_email='from@example.com',recipient_list=['to@example.com'],context={},create_link=True)And, finally add the link to your template.<!-- With the 'if' the link will only appear on the email. -->{% if email_uuid %}<!-- Note: you will need to add your site since you will need to access
             it from the email -->You can view this e-mail on the web here:<ahref="http://www.yoursite.com{% url 'templated_email:show_email' uuid=email_uuid %}">here</a>{% 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 useInlineImageall images will be uploaded to your media storage,
keep that in mind too.Class Based ViewsIt’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:fromtemplated_email.generic_viewsimportTemplatedEmailFormViewMixinclassAuthorCreateView(TemplatedEmailFormViewMixin,CreateView):model=Authorfields=['name','email']success_url='/create_author/'template_name='authors/create_author.html'By default the template will have theform_dataif the form is valid orfrom_errorsif the
form is not valid in it’s context.You can view an examplehereNow you can use the following attributes/methods to customize it’s behavior:Attributes:templated_email_template_name(mandatory if you don’t implementtemplated_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):String containing the email to send the email from.Methods:templated_email_get_template_names(self, valid)(mandatory if you don’t settemplated_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 emailonlywith the first existing template.templated_email_get_recipients(self, form)(mandatory):Return the recipient list to whom the email will be sent to.
ie:deftemplated_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:deftemplated_email_get_context_data(self,**kwargs):context=super(ThisClassView,self).templated_email_get_context_data(**kwargs)# add things to contextreturncontexttemplated_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:deftemplated_email_get_send_email_kwargs(valid,form):kwargs=super(ThisClassView,self).templated_email_get_send_email_kwargs(valid,form)kwargs['bcc']=['admin@example.com']returnkwargstemplated_email_send_templated_mail(*args, **kwargs)(optional):This method calls django-templated-email’ssend_templated_mailmethod. You could change this method to use
a celery’s task for example or to handle errors.Future PlansSeehttps://github.com/vintasoftware/django-templated-email/issues?state=openUsing django_templated_email in 3rd party applicationsIf you would like to use django_templated_email to handle mail in a reusable application, you should note that:Your calls tosend_templated_mailshould set a value fortemplate_dir, so you can keep copies of your app-specific templates local to your app (although the loader will find your email templates if you store them in<your app>/templates/templated_email, ifTEMPLATED_EMAIL_TEMPLATE_DIRhas not been overridden)If you do (and you should) set a value fortemplate_dir, remember to include a trailing slash, i.e.‘my_app_email/’The deployed app may use a different backend which doesn’t use the django templating backend, and as such make a note in your README warning developers that if they are using django_templated_email already, with a different backend, they will need to ensure their email provider can send all your templates (ideally enumerate those somewhere convenient)Notes on specific backendsUsing vanilla_djangoThis is the default backend, and as such requires no special configuration, and will work out of the box. By default it assumes the following settings (should you wish to override them):TEMPLATED_EMAIL_TEMPLATE_DIR='templated_email/'#Use '' for top level template dirTEMPLATED_EMAIL_FILE_EXTENSION='email'For legacy purposes you can specify email subjects in your settings file (but, the preferred method is to use a{% block subject %}in your template):TEMPLATED_EMAIL_DJANGO_SUBJECTS={'welcome':'Welcome to my website',}Additionally you can callsend_templated_mailand optionally override the following parameters:template_prefix='your_template_dir/'  # Override where the method looks for email templates (alternatively, use template_dir)
template_suffix='email'               # Override the file extension of the email templates (alternatively, use file_extension)
cc=['fubar@example.com']              # Set a CC on the mail
bcc=['fubar@example.com']             # Set a BCC on the mail
template_dir='your_template_dir/'     # Override where the method looks for email templates
connection=your_connection            # Takes a django mail backend connection, created using **django.core.mail.get_connection**
auth_user='username'                  # Override the user that the django mail backend uses, per **django.core.mail.send_mail**
auth_password='password'              # Override the password that the django mail backend uses, per **django.core.mail.send_mail**Releasing a new version of this package:Update CHANGELOG file.Execute the following commands:bumpversion [major,minor,patch]
python setup.py publish
git push origin --tagsCommercial SupportThis project, as otherVinta Softwareopen-source projects is used in products of Vinta’s clients. We are always looking for exciting work, so if you need any commercial support, feel free to get in touch:contact@vinta.com.br