Send a dynamic template email from Django & Sendgrid

In this post, we will understand how to send an email from Django based on a dynamic template created in Sendgrid.

Upidev: Send a dynamic template email with Sendgrid and Django

I struggled a bit with the existing documentation and dive into the Sendgrid Python library to find how everything was integrated together. This post is the result of a few intensive hours of research.

Create a Sendgrid Account

Click here to create a Sendgrid account for Free

Create a dynamic template

In order to create a new dynamic template, a template design is required. Let’s start by creating it.

Go to Dashboard -> Design Library -> Create a new design.

Upidev: Send an email with a dynamic template from Django

In the Tags tab, dynamic parameters currently used are listed.

You can also create custom fields directly in the template.

Save your design and come back to your Sendgrid Dashboard.

We need now to create a dynamic template for it.

Dashboard -> Email API -> Dynamic Template

Once created, a template id will appear.

Keep somewhere safe, you will need it later.

Send an email with a dynamic template from Django

To get your API keys, go to Dashboard -> Settings -> API Keys.

By default, API Credentials should already be created for you. If not create new ones.

Now, it is time to install the Django Sendgrid library into your project.

pip install django-sendgrid-v5

And copy the following settings into your settings file. SENDGRID_API_KEY is the key previous found/created in the previous step.

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"

# Toggle sandbox mode (when running in DEBUG mode)

# echo to stdout or any other file-like object that is passed to the backend via the stream kwarg.

Almost done, the last bit is to send the email with a template and parameters.

I did some experiments and concluded that msg.attach_alternative is needed to receive the email in HTML even if the content used is from the template.

def send_welcome_email(user):

    Send a welcome email to a new user'

    msg = EmailMultiAlternatives(
        from_email="Alex <>",
        reply_to=["Alex <>"],
    msg.template_id = '<template-id-from-your-dynamic-template>'
    msg.attach_alternative('<h1></h1>', 'text/html')

    msg.dynamic_template_data = {
        'first_name': user.first_name,

    sendgrid_backend = SendgridBackend()
    response = sendgrid_backend.send_messages([msg])

    return response


I hope you enjoyed this post. If you have any questions, please let me know in comments.

If you liked this post, help us by giving a like or sharing this post.

To know more about me: [FR version]



Laisser un commentaire