0

I created a nice template via the SendGrid UI and am encountering issues trying to send emails with it via the sendgrid python API wrapper (v5.4.1). I've got the template id for a template that has the following (truncated) text:

Hello, {{name}}!

Click the following link to verify your account: {{verification_url}}.

However, when following the example in the documentation, I get a 400 Bad Request error whenever I include the personalizations. I am including the personalizations as follows:

mail.personalizations[0].add_substitution(Substitution("{{name}}", "Example User"))

In addition, mail.get() returns the following:

{
  'from': {
    'email': 'test@school.edu'
  },
 'subject': 'Account Verification',
 'personalizations': 
    [
      {
        'to': [{'email': 'testemail@test.com'}],
        'substitutions': {
                          '{{name}}': 'Example User'}
                         }
    ],
 'template_id': '<template_id_here>'
}

Is there any way to debug what's going on? A 400 Bad Request unfortunately isn't all that helpful...

It looks like these features are actually not yet supported: https://github.com/sendgrid/sendgrid-python/issues/591

David Hagan
  • 1,156
  • 12
  • 23

2 Answers2

0

I ran into this issue a couple of weeks ago as well. The format for substitutions has been changed to use dynamic_template_data.

Instead of:

    mail.personalizations[0].add_substitution(Substitution("{{name}}", "Example User"))

Use:

    mail.personalizations[0].dynamic_template_data = Substitution("name", "Example User").get()

The get() returns a JSON ready version of the substitution. Additionally make sure that you're using at least version 5.6.0 of the Sendgrid API. This feature was just added, here's a link to the github commit: https://github.com/sendgrid/sendgrid-python/commit/4be8d580ec15f1f10180a562aeace8478f76597e

Mr. Chimpanzee
  • 376
  • 1
  • 7
0

There is a recent change from API V3, this works for me

import os import sendgrid from sendgrid.helpers.mail import Mail, Email, Personalization

    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    mail = Mail()
    mail.from_email = Email('customerservice@jafutexpress.com.ng')
    mail.subject = "You are welcome!"
    mail.template_id = 'template_id'
    p = Personalization()
    p.add_to(Email('test@example.com'))
    p.dynamic_template_data = {
    'name': 'Bob',
    }
    mail.add_personalization(p)
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.headers)
    print(response.body)
Abdulhakim
  • 655
  • 6
  • 9