How to show the value of my variables when sending an email from AWS SES with python?

I’m using AWS SES to send emails in a lambda and I’m also consuming an API, I used the aws template for python and it works for sending emails with normal HTML, however when I place the HTML that my boss gave me, it sends errors it doesn’t show the values ​​of the variables, at first I thought of using jinja or format() but when I check the email I only see the braces {{}}, for example I have: ID: {{id}} in my but in my email doesn’t show ID: 4545431, it shows the same as the ID: {{id}}, the value doesn’t appear. In a forum they told me that AWS SES uses handlebars for the most advanced email configuration. I found it in the documentation and it is something like what I want to show, except that when I implement it again, when I check the email, an ID: {{id}} appears again, It doesn’t show any value, what can I do? what am I doing wrong?

import boto3
import requests
from botocore.exceptions import ClientError
from jinja2 import Template

def obtener_informacion_api():
    base_url = ""
    endpoint = "/assignments"
    headers = {
        "auth": "**********************************"

        response = requests.get(f"{base_url}{endpoint}", headers=headers)
        if response.status_code == 200:
            return response.json()
            print(f"Error en la petición a la API. Código de estado: {response.status_code}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error al hacer la petición a la API: {e}")
        return None

def lambda_handler(event, context):

    # Especifica tu región y credenciales aquí
    aws_region = 'us-east-1'
    aws_access_key = '**************************'
    aws_secret_key = '***************************'
    # Obtener información de la API
    api_data = obtener_informacion_api()

    #number_week = api_data.get("NumberWeek")

    if api_data is not None:
        # Procesar la información obtenida de la API
        for asignacion in api_data:

        # Intentar enviar el correo
            # Configuración para enviar el correo a través de SES
            SENDER = "Capacidad Operativa <no-reply@d****.com>"
            RECIPIENT = "i*****@d****.com"
            #CONFIGURATION_SET = "ConfigSet"
            AWS_REGION = "us-east-1"
            SUBJECT = "Prueba de Amazon SES (SDK para Pyt235hon)"
            BODY_TEXT = "Prueba de Amazon SES (Python)\r\nEste correo electrónico fue enviado con Amazon SES usando el SDK de AWS para Python (Boto)."
            # El cuerpo HTML del correo electrónico.

            BODY_HTML ="""<!DOCTYPE html>
                <meta charset="UTF-8">
<body style="background-color: #FFFF;">
  "Template": {
    "TemplateName": "Preferences",
    "SubjectPart": "Subscription Preferences",
    "HtmlPart": "<h1>Your Preferences</h1>
                 <p>You have indicated that you are interested in receiving 
                   information about the following subjects:</p>
                  {% for asignacion in asignaciones %}
        <li>{{ asignacion['id'] }} - {{ asignacion['description'] }} - {{ asignacion['bill_rate'] }}</li>
    {% endfor %}   
             {{#each data}}
               <p>Assignment ID: {{id}}</p>
               <p>Interest Description: {{description}}</p>
               <p>Bill Rate: {{bill_rate}}</p>
                 <p>You can change these settings at any time by visiting 
                    the <a href=>
                    Preference Center</a>.</p>",
    "TextPart": "Your Preferences\n\nYou have indicated that you are interested in 
                 receiving information about the following subjects:\n
                 \nYou can change these settings at any time by 
                 visiting the Preference Center at 

            # Codificación de caracteres para el correo.
            CHARSET = "UTF-8"

            # Crear un nuevo recurso de SES y especificar una región.
            client = boto3.client(

            # Intentar enviar el correo.
                # Proporcionar el contenido del correo electrónico.
                response = client.send_email(
                        "ToAddresses": [
                        "Body": {
                            "Html": {
                                "Charset": CHARSET,
                                "Data": BODY_HTML,
                            "Text": {
                                "Charset": CHARSET,
                                "Data": BODY_TEXT,
                        "Subject": {
                            "Charset": CHARSET,
                            "Data": SUBJECT,
                    # Si no estás utilizando un conjunto de configuración, comenta o elimina la siguiente línea.
            # Mostrar un error si algo sale mal.
            except ClientError as e:
                print("Correo electrónico enviado! ID del mensaje:")

            print("Error al obtener información de la API")

if __name__ == "__main__":
    event = {}
    context = {}
    lambda_handler(event, context)

You’re not using jinja: you’re importing Template from jinja2, but you’re not using it anywhere.

1 Like

At first I was testing with Jinja but it didn’t work, until they told me about the handlebars, I saw the example of the implementation in AWS and I saw that it is very similar to what I was doing, so I preferred to continue with the handlebars

I think you are not doing what the docs say you should be doing to make this work.
I would advise you to go back to the handlebars documentation and read it completely and carefully. Also, carefully compare what you are actually doing and what the docs say you should be doing with templated mails. (If you cannot figure it out in 15 to 20 min, then also consider the hint that Matthew gave you earlier - it may suddenly become clear then.)

1 Like