SendGrid - Sending email with variables using Python
                
            
            
            
             
            
            
                           
                

            
            
            
                
    
    
     
            
                
                    by
                    Jeremy Canfield  |  
                    Updated: October 05 2024
                    
                          |  SendGrid articles
                    
                    
                    
                
            
            This assume you are already familiar with sending a basic sendgrid email template using Python. If not, check out my article Sending email using Python.
In the SendGrid console, select Design Library > Your Images and select one of your images.

And make note of the image URL.

dynamic_template_data can be used to pass variables into a SendGrid email template. This is just the boilerplate code, no error handling, just to focus on the most important markup. In this example, notice the image_url variable is the image URL.
- image_url = cdn.mcauto-images-production.sendgrid.net/dfkj234lkj234lkj/f0c9514b-13a6-4805-bdf0-02d36cbc2505/1800x902.png
#!/usr/bin/python3
import base64
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, To)
message = Mail(
    from_email='from@example.com',
    to_emails=[To('john.doe@example.com'), To('jane.doe@example.com')]
    subject='hey',
    html_content='Hello <strong>World</strong>')
message.dynamic_template_data = {'image_url': 'cdn.mcauto-images-production.sendgrid.net/dfkj234lkj234lkj/f0c9514b-13a6-4805-bdf0-02d36cbc2505/1800x902.png'}
sg = SendGridAPIClient('YOUR API KEY')
response = sg.send(message)
print(f"response.status_code = {response.status_code}")
print(f"response.body        = {response.body}")
print(f"response.headers     = {response.headers}")
Did you find this article helpful?
If so, consider buying me a coffee over at 