unsent
unsent.dev
Guides

Next.js

How to send emails with Unsent in Next.js

Introduction

This guide shows how to send emails using Unsent in a Next.js application. We'll cover both the App Router and Pages Router.

Install dependencies

npm install @unsent/sdk
pnpm add @unsent/sdk
yarn add @unsent/sdk
bun add @unsent/sdk

Configure API Key

Add your Unsent API key to your environment variables file (.env.local).

.env.local
UNSENT_API_KEY=un_...

Send Email

App Router

Create a Route Handler in app/api/send/route.ts.

app/api/send/route.ts
import { Unsent } from '@unsent/sdk';

const unsent = new Unsent(process.env.UNSENT_API_KEY);

export async function POST() {
  try {
    const { data, error } = await unsent.emails.send({
      from: 'Acme <onboarding@unsent.dev>',
      to: ['delivered@unsent.dev'],
      subject: 'Hello world',
      html: '<strong>It works!</strong>',
    });

    if (error) {
      return Response.json({ error }, { status: 500 });
    }

    return Response.json(data);
  } catch (error) {
    return Response.json({ error }, { status: 500 });
  }
}

Pages Router

Create an API route in pages/api/send.ts.

pages/api/send.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { Unsent } from '@unsent/sdk';

const unsent = new Unsent(process.env.UNSENT_API_KEY);

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Method not allowed' });
  }

  try {
    const { data, error } = await unsent.emails.send({
      from: 'Acme <onboarding@unsent.dev>',
      to: ['delivered@unsent.dev'],
      subject: 'Hello world',
      html: '<strong>It works!</strong>',
    });

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

    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
}