Get started with sending emails from Cloudflare Workers in minutes
Send transactional emails from Cloudflare Workers using Lettr’s HTTP API. Workers run on Cloudflare’s global edge network with instant cold starts and zero-millisecond latency — perfect for email APIs that need to be fast anywhere in the world.Using Cursor? Jump straight in using this prompt
import { Lettr } from 'lettr';export interface Env { LETTR_API_KEY: string; FROM_EMAIL?: string;}export default { async fetch(request: Request, env: Env): Promise<Response> { // Only allow POST requests if (request.method !== 'POST') { return new Response('Method not allowed', { status: 405 }); } // Initialize Lettr client const lettr = new Lettr(env.LETTR_API_KEY); try { const body = await request.json() as { to: string | string[]; subject: string; html?: string; text?: string; }; const { to, subject, html, text } = body; // Validate required fields if (!to || !subject || (!html && !text)) { return Response.json( { error: 'Missing required fields: to, subject, and html or text' }, { status: 400 } ); } // Send email const result = await lettr.emails.send({ from: env.FROM_EMAIL || 'noreply@yourdomain.com', to: Array.isArray(to) ? to : [to], subject, html, text, }); console.log(`Email sent successfully. Request ID: ${result.request_id}`); return Response.json({ success: true, requestId: result.request_id, accepted: result.accepted, }); } catch (error: any) { console.error('Failed to send email:', error); return Response.json( { error: error.message || 'Failed to send email' }, { status: error.status || 500 } ); } },};
Cloudflare Workers use the Env interface to define environment variables and secrets. The Lettr SDK automatically handles retries and provides detailed error messages.