Bootstrap FreeKB - SendGrid - Sending email with variables using Python
SendGrid - Sending email with variables using Python

Updated:   |  SendGrid articles

This assume you are already familiar with sending a basic sendgrid email template using Python. If not, check out my article Sending email using Python.

dynamic_template_data can be used to pass variables into a SendGrid email template. This is just the boilerplate code, no error handling, just to focus on the most important markup. In this example, there are two variables.

  • foo = hello
  • bar = world
#!/usr/bin/python3
import base64
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, To)

message = Mail(
    from_email='from@example.com',
    to_emails=[To('john.doe@example.com'), To('jane.doe@example.com')]
    subject='hey',
    html_content='Hello <strong>World</strong>')

message.dynamic_template_data = {'foo': 'hello', 'bar': 'world'}

sg = SendGridAPIClient('YOUR API KEY')
response = sg.send(message)

print(f"response.status_code = {response.status_code}")
print(f"response.body        = {response.body}")
print(f"response.headers     = {response.headers}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 728422 in the box below so that we can be sure you are a human.