Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendGrid Python API Dynamic Template Data

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?

like image 781
Hunter Avatar asked Oct 16 '25 03:10

Hunter


1 Answers

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)
like image 71
jacko_iced_out Avatar answered Oct 18 '25 15:10

jacko_iced_out



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!