Skip to main content

Cloudflare Workers Integration

Learn how to send emails from Cloudflare Workers using Lettr.

Prerequisites

  • Cloudflare account
  • Wrangler CLI installed
  • Lettr API key

Setup

Create a new Workers project:
npm create cloudflare@latest -- my-email-worker
cd my-email-worker
Install the Lettr SDK:
npm install lettr

Worker Code

import { Lettr } from 'lettr';

export interface Env {
  LETTR_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method !== 'POST') {
      return new Response('Method not allowed', { status: 405 });
    }

    const lettr = new Lettr(env.LETTR_API_KEY);
    
    try {
      const { to, subject, html } = await request.json();
      
      await lettr.emails.send({
        from: 'you@example.com',
        to: [to],
        subject,
        html
      });

      return Response.json({ success: true });
    } catch (error) {
      return Response.json(
        { error: error.message },
        { status: 500 }
      );
    }
  }
};

Using Fetch API Directly

If you prefer not to use the SDK:
export interface Env {
  LETTR_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { to, subject, html } = await request.json();
    
    const response = await fetch('https://api.lettr.dev/v1/emails', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env.LETTR_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        from: 'you@example.com',
        to: [to],
        subject,
        html
      })
    });

    return Response.json(await response.json());
  }
};

Configure Secrets

Add your API key as a secret:
npx wrangler secret put LETTR_API_KEY

wrangler.toml Configuration

name = "my-email-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[vars]
# Non-sensitive configuration
FROM_EMAIL = "you@example.com"

Deploy

npx wrangler deploy
Cloudflare Workers have excellent cold start performance, making them ideal for email sending endpoints.