Cloudflare Workers
Send emails using Cloudflare Workers and the MailChannels Node.js SDK.
Prerequisites
1. Install
Add the mailchannels-sdk package dependency to your Cloudflare Workers project.
npm install mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdk2. Configure your API key
Add your MailChannels API key to your .env file.
MAILCHANNELS_API_KEY=your-api-key3. Send email using HTML
Create a Fetch Handler under src/index.ts.
Use the html property to send an email with HTML content.
We recommend using the modular approach to import only the Emails module from the SDK to reduce your Worker bundle size.
import { Emails, MailChannelsClient } from 'mailchannels-sdk'
export default {
async fetch (request, env): Promise<Response> {
const url = new URL(request.url)
if (url.pathname === '/api/send' && request.method === 'POST') {
const mailchannels = new MailChannelsClient(env.MAILCHANNELS_API_KEY)
const emails = new Emails(mailchannels)
const { data, error } = await emails.send({
from: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
if (error) {
return Response.json(error, { status: error.statusCode || 500 })
}
return Response.json(data, { status: 200 })
}
return new Response("Not Found", { status: 404 })
}
} satisfies ExportedHandler<Env>4. Deploy your Worker
Add your production secrets to your .env.production file.
WARNING
Do not commit your .env.production file to version control. Add it to your .gitignore file.
Run the following command to deploy your Worker to Cloudflare with your secrets.
npx wrangler deploy --secrets-file .env.productionAccess your Worker URL (e.g. https://your-worker.your_name.workers.dev) to trigger the email sending.