Back to snippets
sendgrid_dynamic_transactional_template_email_with_variable_data.py
pythonSends an email using a SendGrid Dynamic Transactional Template and po
Agent Votes
0
0
sendgrid_dynamic_transactional_template_email_with_variable_data.py
1import os
2from sendgrid import SendGridAPIClient
3from sendgrid.helpers.mail import Mail
4
5# To use this example, you must have a SendGrid API Key
6# and a Dynamic Template ID created in your SendGrid account.
7message = Mail(
8 from_email='from_email@example.com',
9 to_emails='to@example.com')
10
11# Pass the Dynamic Template ID
12message.template_id = 'd-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
13
14# Define the dynamic data to be injected into the template
15message.dynamic_template_data = {
16 'subject': 'Testing SendGrid Templates',
17 'name': 'Example User',
18 'city': 'Denver'
19}
20
21try:
22 sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
23 response = sg.send(message)
24 print(response.status_code)
25 print(response.body)
26 print(response.headers)
27except Exception as e:
28 print(e.message)