Skip to main content

AWS Lambda Integration

Learn how to send emails from AWS Lambda functions using Lettr.

Prerequisites

  • AWS account with Lambda access
  • Lettr API key
  • Node.js or Python runtime

Node.js Example

import { Lettr } from 'lettr';

const lettr = new Lettr(process.env.LETTR_API_KEY);

export const handler = async (event) => {
  try {
    const { to, subject, html } = JSON.parse(event.body);
    
    await lettr.emails.send({
      from: 'you@example.com',
      to: [to],
      subject,
      html
    });

    return {
      statusCode: 200,
      body: JSON.stringify({ message: 'Email sent successfully' })
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: error.message })
    };
  }
};

Python Example

import json
import os
from lettr import Lettr

lettr = Lettr(os.environ['LETTR_API_KEY'])

def handler(event, context):
    try:
        body = json.loads(event['body'])
        
        lettr.emails.send(
            from_email='you@example.com',
            to=[body['to']],
            subject=body['subject'],
            html=body['html']
        )
        
        return {
            'statusCode': 200,
            'body': json.dumps({'message': 'Email sent successfully'})
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }

Environment Variables

Set your API key as an environment variable in the Lambda console or via AWS CLI:
aws lambda update-function-configuration \
  --function-name your-function-name \
  --environment "Variables={LETTR_API_KEY=your-api-key}"

Using AWS Secrets Manager

For production, consider using AWS Secrets Manager:
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
import { Lettr } from 'lettr';

const secretsManager = new SecretsManagerClient({ region: 'us-east-1' });
let lettr;

async function getLettrClient() {
  if (!lettr) {
    const response = await secretsManager.send(
      new GetSecretValueCommand({ SecretId: 'lettr-api-key' })
    );
    lettr = new Lettr(response.SecretString);
  }
  return lettr;
}

export const handler = async (event) => {
  const client = await getLettrClient();
  // ... send email
};

Layer Deployment

Create a Lambda Layer for the Lettr SDK:
mkdir -p nodejs
cd nodejs
npm init -y
npm install lettr
cd ..
zip -r lettr-layer.zip nodejs
aws lambda publish-layer-version \
  --layer-name lettr-sdk \
  --zip-file fileb://lettr-layer.zip \
  --compatible-runtimes nodejs18.x nodejs20.x