Send
Send a predefined email using the API route
Send emails using Next.js and the MailChannels Node.js SDK.
Add the mailchannels-sdk package dependency to your Next.js project.
npm i mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdkbun add mailchannels-sdkdeno add npm:mailchannels-sdkAdd your MailChannels API key to your .env file.
MAILCHANNELS_API_KEY=your-api-keyRegister an App route handler under app/api/send/route.ts or a Pages API route under pages/api/send.ts.
Use the html property to send an email with HTML content.
import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels(process.env.MAILCHANNELS_API_KEY)
export async function POST () {
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 Response.json(error, {
status: error.statusCode || 400
})
}
return Response.json(data)
}import type { NextApiRequest, NextApiResponse } from 'next'
import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels(process.env.MAILCHANNELS_API_KEY)
export default async function handler (req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST')
return res.status(405).json({ error: 'Method Not Allowed' })
}
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 })
}
return res.status(200).json(data)
}