Skip to content

FrameworksNext.js

Send email from Next.js with Shipmail

Send your app's email from Server Actions and Route Handlers with the shipmail SDK. Email goes out from your sending subdomain, and replies reach your Shipmail mailbox.

Last updated

Before you start

  • A verified sending subdomain, such as notify.example.com, with an active sender. See Transactional email.
  • An API key with send access to the sender's mailbox.
  • The sender address, such as hello@notify.example.com. Use the bare address. Shipmail adds the sender name.

Install the SDK

Add the SDK and put the key and the sender address in your environment. Keep the key on the server. Never give it a NEXT_PUBLIC_ name.

bun add shipmail
# .env.local
SHIPMAIL_API_KEY=sm_live_...
EMAIL_FROM=hello@notify.example.com

Add a sendEmail helper

server-only makes the build fail if a Client Component imports the helper. The SDK throws if Shipmail refuses the send.

// lib/email.ts
import "server-only";
import { ShipmailClient } from "shipmail";

const shipmail = new ShipmailClient(process.env.SHIPMAIL_API_KEY!);

type Email = { to: string; subject: string; text?: string; html?: string };

export async function sendEmail({ to, ...content }: Email) {
  await shipmail.messages.send({ from: process.env.EMAIL_FROM, to: [to], ...content });
}

Send from a Server Action

after() sends the email once the response is on its way, so the user does not wait for it.

// app/actions.ts
"use server";

import { after } from "next/server";
import { sendEmail } from "@/lib/email";

export async function signUp(formData: FormData) {
  const email = String(formData.get("email"));
  // Create the account here.

  after(() =>
    sendEmail({ to: email, subject: "Welcome to Acme", text: "Thanks for signing up." }),
  );
}

Send from a Route Handler

// app/api/contact/route.ts
import { sendEmail } from "@/lib/email";

export async function POST(request: Request) {
  const { email } = await request.json();
  await sendEmail({
    to: email,
    subject: "We got your message",
    text: "We will reply soon.",
  });
  return Response.json({ ok: true });
}

Test without sending

Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode.