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-sdksh
yarn add mailchannels-sdksh
pnpm add mailchannels-sdksh
bun add mailchannels-sdksh
deno add npm:mailchannels-sdk2. Configure your API key
Add your MailChannels API key to your .env file.
sh
MAILCHANNELS_API_KEY=your-api-key3. 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.
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')
})