Skip to main content

A BaseApp app that allows the use of customizable e-mail and sms templates.

Project description

BaseApp Message Templates - Django

This app provides the integration of custom e-mail and sms template configuration with The SilverLogic's BaseApp.

Install the package

Add to requirements/base.txt:

git+https://bitbucket.org/silverlogic/baseapp-message-templates-django.git

Configure template settings

TEMPLATES  =  [
	{
		"BACKEND": "django_jinja.backend.Jinja2",
		"DIRS": [str(APPS_DIR  /  "templates")], # change this to wherever your base templates are stored
		"APP_DIRS": True,
        "NAME": "jinja2",
		"OPTIONS": {
			"match_extension": ".j2",
			"constants": {"URL": URL, "FRONT_URL": FRONT_URL},
		},
	},
	{
		"BACKEND": "django.template.backends.django.DjangoTemplates",
		"DIRS": [
			str(APPS_DIR  /  "templates"), # change this to wherever your base templates are stored
		],
		"APP_DIRS": True,
		"OPTIONS": {
			"context_processors": [
				"django.template.context_processors.debug",
				"django.template.context_processors.request",
				"django.contrib.auth.context_processors.auth",
				"django.contrib.messages.context_processors.messages",
			],
			"libraries": {
				"filter": "baseapp_message_templates.filters",
			},
		},
	},
]

Default Email Template

In our Django application, you have the option to use a default email template. This template acts as a wrapper for your other email templates, ensuring a consistent layout and style across all your emails.

Using the Default Template

To effectively utilize the default template:

  1. Create the Default Template

    Ensure your default template includes a placeholder for the child template content. This is done using the template_content|safe variable in your Jinja2 template.

    Example:

    <html>
    <body>
      <div>
        <!-- Your default template layout -->
        <div class="content">
          {{ template_content|safe }}
        </div>
        <!-- More of your default template layout -->
      </div>
    </body>
    </html>
    
  2. Render Child Templates

    When rendering a child template, pass the content as a string to template_content. Jinja2 will insert this content into the default template at the location of {{ template_content|safe }}.

  3. Sanitize for Security: To ensure security, especially since we're using the safe filter, it's important to sanitize template_content to prevent XSS (Cross-Site Scripting) attacks. This process removes or neutralizes any potentially harmful scripts that might be part of the content.

Setting Default Base Template (Optional)

If you want to use a default base template that your emails will automatically inherit from, add the path to that template in your Django settings. This configuration allows you to define a consistent layout or design for your emails. Note that this base template won't apply to emails created directly in SendGrid.

In your settings.py:

DEFAULT_EMAIL_TEMPLATE = "path/to/your/default/template" # ex: "emails/base-template"

Setup SendGrid credentials (optional)

If you want to use SendGrid to send mail, add these settings to your settings/base.py:

DJMAIL_REAL_BACKEND = "sendgrid_backend.SendgridBackend"

SENDGRID_API_KEY = env("SENDGRID_API_KEY")

SENDGRID_SANDBOX_MODE_IN_DEBUG = False

EmailTemplate model

This model is responsible for customizing your e-mail template and sending mail. At minimum, an instance of EmailTemplate must have a unique name and either a SendGrid template ID or some custom HTML content. The subject, plain_text_content, and attachments are optional.

Static attachments

Attachment instances that are linked to an EmailTemplate represent static files that will be attached to every message sent via that template, regardless of recipient or context. These attachments will be sent regardless of whether the e-mail is sent through a SendGrid template or a custom HTML template.

Sending mail via SendGrid template

If a sendgrid_template_id is provided on an instance of EmailTemplate, a SendGrid template can be used to send mail. In order to send mail via SendGrid template, at least one Personalization must first be created. Each Personalizationwill contain the email of a recipient and any context that must be provided to the template. A Personalization can be created like so:

from baseapp_message_templates.sendgrid import get_personalization

personalization = get_personalization("john@test.com", {"message": "Hello there."})

Sending mail to one recipient

The send_via_sendgrid method of EmailTemplate can be used to send a single email to one recipient. The method takes one Personalization as an argument, as well as an optional list of attachments that can be sent along with this particular message.

from baseapp_message_templates.models import EmailTemplate
from baseapp_message_templates.sendgrid import get_personalization

template = EmailTemplate.objects.get("Test Template")

personalization = get_personalization("john@test.com", {"message": "Hello there."})

template.send_via_sendgrid(personalization)

Sending mail to multiple recipients

The mass_send_via_sendgrid method of EmailTemplate can be used to send multiple instances of a template to multiple recipients. The method takes a list of Personalization objects as an argument, and each Personalization will send a separate message to each recipient with its own context.

from baseapp_message_templates.models import EmailTemplate
from baseapp_message_templates.sendgrid import get_personalization


template = EmailTemplate.objects.get("Test Template")

personalization_1 = get_personalization("john@test.com", {"message": "Hello there."})
personalization_2 = get_personalization("jane@test.com", {"message": "Good morning."})
personalization_list = [personalization_1, personalization_2]

template.mass_send_via_sendgrid(personalization_list)

Sending Mail via custom HTML

If you aren't using SendGrid and instead wish to provide your custom HTML content directly to the EmailTemplate instance, this can be done through the html_content field. Once html_content has been provided, the send method of the EmailTemplate can be used to send mail.

Adding HTML content via Django Admin

When adding HTML content to a template through the Django Admin, the "source" option must be selected in the text field.

enter image description here

After saving, the content of the text field will no longer contain the raw HTML that was added. This is a small caveat of the Django Admin. The "raw HTML" field that is displayed underneath the input will display the actual raw HTML content that is currently added to the instance.

enter image description here

Sending

Once you've added html_content to your template, either programatically or through the Django Admin, a message can now be sent through the send method of EmailTemplate.

The only required parameter for send is recipients, which is a list of one or more strings containing the e-mail addresses of the recipients. A context dict can be passed in optionally if the HTML content is expected one or more key/value pairs to be provided.

The use_base_template flag will determine whether this message should extend from a base HTML template. If set to True, the message will extend from the base template that is located at a certain path. This path will either be the value of extended_with if provided, or the value of DEFAULT_EMAIL_TEMPLATE.

Finally, the attachments parameter is a list of one or more files that will be send along with this particular message. These attachments will be sent along with any static attachments that have been attached to the template itself through Attachment.

from baseapp_message_templates.models import EmailTemplate


template = EmailTemplate.objects.get("Test Template")

recipients = ["john@test.com"]
context = {"content": "Hello."}
extended_with = "apps/base/templates/test-template.html"

template.send(recipients, context, True, extended_with)

SmsTemplate Model

The SmsTemplate model has two fields:

  • name: this name must be unique.
  • message: this is a textfield and does not accept HTML

Creating migrations for your template

Once you have installed the package you can simply create a migration to input your templates like so:

from __future__ import unicode_literals

from django.db import migrations


def create_object(sms_template, name, message):
    sms_template.objects.create(
        name=name,
        message=message,
    )


def create_sms_templates(apps, schema_migration):
    sms_template = apps.get_model("baseapp_message_templates", "SmsTemplate")

    create_object(
        sms_template,
        "First Template",
        """
            Hello, {{ some_variable }}.
        """,
    )

    create_object(
        sms_template,
        "Second template",
        """
            Hello, {{ some_other_variable }}.
        """,
    )


class Migration(migrations.Migration):
    dependencies = [("some_app", "0002_some_previus_migration")]

    operations = [migrations.RunPython(create_sms_templates, migrations.RunPython.noop)]

OBS: make sure that the variables are the right ones that you will pass as context when getting the message.

Get the template message

To get the template message you can simply use the util functions get_sms_message from sms_utils passing as first parameter the name of the template and the second parameter the context with your variables if needed.

from baseapp_message_templates.sms_utils import get_sms_message

context = {"some_variable": "some_value"}

message = get_sms_message("First Template", context)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

baseapp-message-templates-1.6.tar.gz (15.4 kB view details)

Uploaded Source

File details

Details for the file baseapp-message-templates-1.6.tar.gz.

File metadata

File hashes

Hashes for baseapp-message-templates-1.6.tar.gz
Algorithm Hash digest
SHA256 564f79bfb504792c93efa22995220ade69a30106efb935809f7796a0ae9e1b94
MD5 55b9b7950015d71a5e511b38c80a7075
BLAKE2b-256 22dbd1f39c1b525bf8edb7e9b222da0a713bc5575fae048c678b27e8b6d6413c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page