I have a python script that pulls customer transaction data from our DB and formats it to be used by SendGrid's Dynamic Templates, but I cannot figure out from the SendGrid docs or any other source how to insert each customer's unique data in their email. Here is the relevant code from the script (assume all variables are pre-filled by the script):
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To
message = Mail(
from_email=("[email protected]", "My Website"),
to_emails=to_emails,
is_multiple=True)
message.template_id = "d-thetemplateidthatiamusing"
try:
sendgrid_client = SendGridAPIClient("SG.thesecretkeythatdoesnotbelongonstack")
sendgrid_client.send(message)
except Exception as e:
print(e)
When I run this, it sends to the correct customer emails, but without any custom data. I have the following object ready to send over for each customer, but have no idea how to attach it on an email by email basis:
{
"name": "Customer Name",
"games": [
{
"game_title": "Test Team vs. Demo Team",
"event_name": "Live Showcase I",
"date": "5/9/2021",
"score": "79-55",
"url": "app.website.com/"
},
{
"game_title": "Test Team vs. Demo Team",
"event_name": "Live Showcase I",
"date": "5/9/2021",
"score": "79-69",
"url": "app.website.com/"
}
]
}
When I throw this JSON in the SendGrid template test data area it works perfectly with my design. Any thoughts?
You are missing an attribute:
message.dynamic_template_data = {
"name": "Customer Name",
}
To pass information dynamically you need to pass an instance of the Customer to your email dispatcher:
def sendEmail(instance):
message = Mail(
from_email=("[email protected]", "My Website"),
to_emails=to_emails,
is_multiple=True)
message.dynamic_template_data = {
"name":instance.name
}
message.template_id = "d-thetemplateidthatiamusing"
try:
sendgrid_client = SendGridAPIClient("SG.thesecretkeythatdoesnotbelongonstack")
sendgrid_client.send(message)
except Exception as e:
print(e)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With