Skip to content

Cloudflare Workers

Send emails using Cloudflare Workers and the MailChannels Node.js SDK.

Deploy to Cloudflare

Prerequisites

1. Install

Add the mailchannels-sdk package dependency to your Cloudflare Workers project.

sh
npm install mailchannels-sdk
sh
yarn add mailchannels-sdk
sh
pnpm add mailchannels-sdk

2. Configure your API key

Add your MailChannels API key to your .env file.

.env
sh
MAILCHANNELS_API_KEY=your-api-key

3. 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.

src/index.ts
ts
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.

sh
npx wrangler deploy --secrets-file .env.production

Access your Worker URL (e.g. https://your-worker.your_name.workers.dev) to trigger the email sending.

Released under the MIT License.