Skip to content

Next.js

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

Prerequisites

1. Install

Add the mailchannels-sdk package dependency to your Next.js 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 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.

ts
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)
}
ts
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)
}

Examples

Released under the MIT License.