Send with

Send email with Next.js

Send email from the server side of your Next.js app: a Route Handler or a Server Action. Never expose your API key to the browser.

Environment variable

# .env.local (not prefixed with NEXT_PUBLIC_, so it stays on the server)
ROBUSTEMAIL_API_KEY=rb_test_...

A helper

// lib/robustemail.ts
const API = "https://robustemail.com/api/v2";

export async function sendEmail(email: Record<string, unknown>, idempotencyKey?: string) {
  const res = await fetch(`${API}/emails`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ROBUSTEMAIL_API_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: JSON.stringify(email),
    cache: "no-store",
  });
  const body = await res.json();
  if (!res.ok) throw new Error(`${body.name}: ${body.message}`);
  return body.id as string;
}

Route Handler

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

export async function POST(request: Request) {
  const { name, email, message } = await request.json();

  const id = await sendEmail({
    from: "Acme Website <website@acme.com>",
    to: "team@acme.com",
    reply_to: email,
    subject: `New message from ${name}`,
    text: message,
  });

  return Response.json({ id });
}

Server Action

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

import { sendEmail } from "@/lib/robustemail";

export async function sendWelcome(userId: string, address: string) {
  await sendEmail(
    {
      from: "Acme <hello@acme.com>",
      to: address,
      subject: "Welcome to Acme",
      html: "<h1>Welcome!</h1><p>Your account is ready.</p>",
    },
    `welcome-${userId}`,
  );
}

Validate form input before sending, and rate-limit public forms so they cannot be used to send spam through your account.

Next