Hunter
Hunter

Reputation: 458

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?

Upvotes: 4

Views: 9122

Answers (3)

DINA TAKLIT
DINA TAKLIT

Reputation: 8388

just to add to what @jacko_iced_out answered, in SendGrid you should wrap the variable you want to set with {{}}

 <div class="v-font-size" style="color: #444444; line-height: 170%; text-align: center; word-wrap: break-word;">
    <p style="font-size: 14px; line-height: 170%;">
      <span style="font-size: 20px; line-height: 34px;">
        <strong>
          <span style="line-height: 34px;">{{password}}</span>
        </strong>
      </span>
    </p>
</div>

And here is an example of python code to send mail

from fastapi import  HTTPException
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from config import settings


async def sendLoginMailClient(admin_mail, client_mail, password):
    message = Mail(
        subject='Invitation de création de maturité numirique profil',
        from_email=("from_sendgridmail_mail"),
        to_emails=client_mail
    )
    message.dynamic_template_data = {
        "admin": admin_mail,
        'client': client_mail,
        "password": password
    }
    message.template_id = "d-c9f1894881ff426aa614e5c41e831f16"
    try:
        sg = SendGridAPIClient(settings.sendgrid_api_key)
        response = sg.send(message)
        code = response.status_code

        return {
            'success': True,
            'data': code
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f'error:{e}'
        )

For more detail check this link https://www.twilio.com/blog/send-dynamic-emails-python-twilio-sendgrid

Upvotes: 2

beeThree
beeThree

Reputation: 154

You did not include your initialization code for to_emails, here is a link to an example that shows how to set dynamic template data for each 'to' email address. Also, it wasn't clear to me, does each recipient have their own set of json data, or is name the only thing difference between them? In other words, would they all be receiving the same data for games?

And here is an excerpt (adjust the recipient and dynamic_template_data to fit your needs):

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To

to_emails = [
    To(email='[email protected]',
       name='Customer Name 0',
       dynamic_template_data={
           'name': 'Customer Name 0',
           'games': games,
       },
       subject='Override Global Subject'),
    To(email='[email protected]',
       name='Customer  Name 1',
       dynamic_template_data={
           'name': 'Customer Name 1',
           'games': games,
       }),
]
message = Mail(
    from_email=('[email protected]', 'Example From Name'),
    to_emails=to_emails,
    subject='Global subject',
    is_multiple=True)
message.template_id = 'd-12345678901234567890123456789012'

try:
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)

Upvotes: 2

jacko_iced_out
jacko_iced_out

Reputation: 33

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)

Upvotes: 3

Related Questions