Skip to content

Express

Send emails using Express and the MailChannels Node.js SDK.

Prerequisites

1. Install

Add the mailchannels-sdk package dependency to your Express project.

sh
npm i mailchannels-sdk
sh
yarn add mailchannels-sdk
sh
pnpm add mailchannels-sdk
sh
bun add mailchannels-sdk
sh
deno add npm: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

Register a /api/send Route handler for your Express app.

Use the html property to send an email with HTML content.

src/app.ts
ts
import express from 'express'
import type { Request, Response } from 'express'
import { MailChannels } from 'mailchannels-sdk'

process.loadEnvFile()

const app = express()
const mailchannels = new MailChannels(process.env.MAILCHANNELS_API_KEY)

app.post('/api/send', async (req: Request, res: Response) => {
  const { data, error } = await mailchannels.emails.send({
    from: 'Name <from@example.com>',
    to: 'to@example.com',
    subject: 'Test email',
    html: '<p>Hello World</p>'
  })

  if (error) {
    return res.status(error.statusCode || 400).json(error)
  }

  res.status(200).json(data)
})

app.listen(3000, () => {
  console.log('Listening on http://localhost:3000')
})

Released under the MIT License.