SendGrid - Sending email with variables using Python
by
Jeremy Canfield |
Updated: February 19 2024
| 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