Bootstrap FreeKB - SendGrid - Sending email with image variables using Python
SendGrid - Sending email with image variables using Python

Updated:   |  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.

 

Then 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, dynamic_template_data contains JSON where the key is image_url and the value is http://cdn.mcauto-images-production.sendgrid.net/dfkj234lkj234lkj/f0c9514b-13a6-4805-bdf0-02d36cbc2505/1800x902.png, which is the SendGrid Image URL.

#!/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': 'http://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}")

 

Then add an image object to your Dynamic Template and select the code button.

 

And in the HTML update the src (source) key to have the image_url variable since image_url is the name of the key used in our Python script.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7a23a6 in the box below so that we can be sure you are a human.