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 file.py but in my email doesn’t show ID: 4545431, it shows the same as the file.py 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 = "https://api.rm.smartsheet.com/api/v1"
endpoint = "/assignments"
headers = {
"auth": "**********************************"
}
try:
response = requests.get(f"{base_url}{endpoint}", headers=headers)
response.raise_for_status()
if response.status_code == 200:
return response.json()
else:
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()
print(api_data)
#number_week = api_data.get("NumberWeek")
#print(number_week)
if api_data is not None:
# Procesar la información obtenida de la API
for asignacion in api_data:
print(asignacion)
# Intentar enviar el correo
try:
# 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>
<head>
<meta charset="UTF-8">
<title>Empresa</title>
</head>
<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>
<ul>
{% 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>
{{/each}}
</ul>
<p>You can change these settings at any time by visiting
the <a href=https://www.example.com/prefererences/i.aspx?id=>
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
}
}
</body>
</html>"""
# Codificación de caracteres para el correo.
CHARSET = "UTF-8"
# Crear un nuevo recurso de SES y especificar una región.
client = boto3.client(
'ses',
aws_access_key_id='*********************',
aws_secret_access_key='********************',
region_name='****'
)
# Intentar enviar el correo.
try:
# Proporcionar el contenido del correo electrónico.
response = client.send_email(
Destination={
"ToAddresses": [
RECIPIENT,
],
},
Message={
"Body": {
"Html": {
"Charset": CHARSET,
"Data": BODY_HTML,
},
"Text": {
"Charset": CHARSET,
"Data": BODY_TEXT,
},
},
"Subject": {
"Charset": CHARSET,
"Data": SUBJECT,
},
},
Source=SENDER,
# Si no estás utilizando un conjunto de configuración, comenta o elimina la siguiente línea.
#ConfigurationSetName=CONFIGURATION_SET,
)
# Mostrar un error si algo sale mal.
except ClientError as e:
print(e.response["Error"]["Message"])
else:
print("Correo electrónico enviado! ID del mensaje:")
print(response["MessageId"])
except:
print("Error al obtener información de la API")
if __name__ == "__main__":
event = {}
context = {}
lambda_handler(event, context)