Abhishek Kaushik
Abhishek Kaushik

Reputation: 117

400 Error Bad Request Dynamic Templates with Substitutions not working in Sendgrid for Python

Issue

I am trying to send multiple emails using a Dynamic Template, with each email having their own unique substitutions using the Mail Helper class. If I don't include the substitutions then the code works perfectly and mails are delivered, but as soon as I include substitution I get a "HTTP Error 400: Bad Request". I am using Virtual Environment and running it in my Flask app. I have installed sendgrid using "pip install sendgrid" and its updated to the latest version.

Code

to_emails = [
        To(
            email='[email protected]',
            name='person1',
            substitutions={
                '-unsubscribeLink-':'https://www.example1.com'
            }
            ),
        To(
            email='[email protected]',
            name='person2',
            substitutions={
                '-unsubscribeLink-':'https://www.example2.com'
            }
            ),
    ]

    message = Mail(
                from_email=From('[email protected]','Website'),
                to_emails=to_emails,
                is_multiple=True)

    message.template_id = 'd-c8d1a24b4539459b831407e2562045a9'
    try:
        sg = SendGridAPIClient('API KEY')
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(str(e))

The Exception

HTTP Error 400: Bad Request

Technical details

sendgrid-python version: I had installed using "pip install sendgrid" and its version is 6.3.1, so I don't think I am using "sendgrid-python". python version: Python 3.6.7

I tried upgrading and this is what it prints :

pip install sendgrid --upgrade

Requirement already up-to-date: sendgrid in ./p37ve/lib/python3.6/site-packages (6.3.1)
Requirement already satisfied, skipping upgrade: python-http-client>=3.2.1 in ./p37ve/lib/python3.6/site-packages (from sendgrid) (3.2.7)

Upvotes: 1

Views: 519

Answers (1)

Swetha Mandava
Swetha Mandava

Reputation: 11

Had the same issue. Turns out they modified the api format. This should fix it!

to_emails = [
        To(
            email='[email protected]',
            name='person1',
            dynamic_template_data={
                '-unsubscribeLink-':'https://www.example1.com'
            }
            ),
        To(
            email='[email protected]',
            name='person2',
            dynamic_template_data={
                '-unsubscribeLink-':'https://www.example2.com'
            }
            ),
    ]

Upvotes: 0

Related Questions