How to Send Email in Next.js: A Route Handler, a Server Action and Delivery Events Tagged by Campaign
Send a welcome email from a Next.js App Router route handler, an invite from a Server Action, and record delivery and bounce events tagged with the signup's campaign source.
Direct answer. To send email in Next.js, call AgentiSend from a route handler or a Server Action, where the API key stays on the server: install agentisend, set AGENTISEND_API_KEY and MAIL_FROM, and call agentisend.emails.send({ from, to, subject, html }, { idempotencyKey }). Add a tags object with the signup's campaign source and a signed webhook route, and every delivery and bounce event comes back labelled with the channel that produced the user. An app that already sends through Nodemailer can switch with the nodemailer-agentisend-transport package instead of rewriting its calls.
Most Next.js email tutorials stop at the send. For a growth team the send is half the job. The welcome email is the first product touch after a paid click, and whether it was delivered, bounced or never sent belongs in the same analysis as the ad spend that produced the signup. This guide covers the send, the second send pattern Next.js offers, and the event route that closes the loop.
How we put this together
Our editors read AgentiSend's Next.js guide, webhook documentation and published examples, plus the other providers' documentation, between 28 September and 10 November 2026, and pricing pages on 9 November 2026. We did not run our own send tests; the code follows the shapes in AgentiSend's tested App Router example.
Providers for a Next.js app, compared
| Provider | Package | Retry-safe sends | Signed webhooks | 50,000 emails/mo |
|---|---|---|---|---|
| AgentiSend | agentisend (Resend-compatible entry included) |
Idempotency-Key, 7 days |
HMAC-SHA256, replay | $16 |
| Resend | Resend SDK | Idempotency-Key, 24 hours |
Not covered here | $20 |
| Postmark | Not covered here | Not supported | Basic auth, IP allow list | $55 |
| Mailgun | Not covered here | Not documented | HMAC-SHA256 | $35 |
| Amazon SES | Not covered here | Not documented | Not covered here | $5 to $8 |
Step 1: install and configure
npm install agentisend
| Variable | Required | What it is |
|---|---|---|
AGENTISEND_API_KEY |
Yes | A key with sending_access. new AgentiSend() reads it. |
MAIL_FROM |
Yes | The From address, on a domain you have verified. |
WEBHOOK_SECRET |
For step 4 | The signing secret returned when you create the webhook endpoint. |
AGENTISEND_BASE_URL |
No | Defaults to https://api.agentisend.com. |
Before your domain verifies, you can still exercise the code: any address at simulator.agentisend.com is accepted, costs nothing and reaches nobody.
Step 2: the welcome email, from a route handler
Save as app/api/welcome/route.ts. Your signup flow posts the new user's email, id and the campaign source you captured at signup (from UTM parameters or a first-touch cookie).
import { AgentiSend, AgentiSendError } from 'agentisend';
const agentisend = new AgentiSend();
export const runtime = 'nodejs';
// Tag values allow letters, digits, _ and - (up to 256 characters).
const tagSafe = (v: string | undefined) =>
(v ?? 'direct').toLowerCase().replace(/[^a-z0-9_-]/g, '_').slice(0, 256);
export async function POST(request: Request): Promise<Response> {
const { email, userId, utmSource, utmCampaign } = (await request.json()) as {
email?: string; userId?: string; utmSource?: string; utmCampaign?: string;
};
if (!email || !userId) return Response.json({ error: 'email and userId are required' }, { status: 400 });
try {
const { id } = await agentisend.emails.send(
{
from: process.env.MAIL_FROM!,
to: email,
subject: 'Your workspace is ready',
html: '<p>Your workspace is ready. Connect your first data source to fill the dashboard.</p>',
tags: { flow: 'welcome', utm_source: tagSafe(utmSource), utm_campaign: tagSafe(utmCampaign) },
},
{ idempotencyKey: `welcome/${userId}` },
);
return Response.json({ id }); // store this against the user row
} catch (err) {
if (err instanceof AgentiSendError) {
return Response.json({ code: err.code, fix: err.fix }, { status: err.status });
}
throw err;
}
}
Three details matter:
- The idempotency key is derived from the user, not the request time. A signup form that retries after a slow response, or a double-click, replays the first send instead of mailing the same person twice. AgentiSend remembers the key for 7 days.
- Tag values are sanitised. Tags accept letters, digits,
_and-, so a source likefacebook.comor a campaign name with spaces needs cleaning before it goes on the message. - The message id is returned. Store it on the user row.
GET /emails/{id}shows its status andGET /emails/{id}/explainsays what happened if it never arrived.
Step 3: a team invite, from a Server Action
For a form that posts straight to the server, save this as app/actions.ts with 'use server' as its first line:
'use server';
import { AgentiSend, AgentiSendError } from 'agentisend';
const agentisend = new AgentiSend();
export async function inviteTeammate(formData: FormData) {
const email = String(formData.get('email') ?? '');
const workspaceId = String(formData.get('workspaceId') ?? '');
if (!email) return { error: { code: 'validation_error', fix: 'Fill in the email field.' } };
try {
const { id } = await agentisend.emails.send(
{
from: process.env.MAIL_FROM!,
to: email,
subject: 'You have been invited to a workspace',
text: 'Open the link in the app to accept the invitation.',
tags: { flow: 'invite' },
},
{ idempotencyKey: `invite/${workspaceId}/${email}` },
);
return { id };
} catch (err) {
if (err instanceof AgentiSendError) return { error: { code: err.code, fix: err.fix } };
throw err;
}
}
Every refusal carries a code and a fix, so the form can show "this address previously bounced" for suppressed_recipient instead of a generic error.
Step 4: record delivery events next to your attribution data
Create a webhook endpoint for email.delivered, email.bounced, email.complained and email.delivery_delayed, and point it at app/api/email-events/route.ts:
import { verifyWebhookSignature } from 'agentisend/webhook-signing';
export const runtime = 'nodejs';
export async function POST(request: Request): Promise<Response> {
const rawBody = await request.text(); // the signature covers these exact bytes
const ok = verifyWebhookSignature(
process.env.WEBHOOK_SECRET!,
request.headers.get('x-agentisend-signature') ?? '',
rawBody,
);
if (!ok) return new Response('invalid signature', { status: 400 });
const event = JSON.parse(rawBody);
await recordEmailEvent({
eventId: request.headers.get('x-agentisend-event-id'), // dedupe on this
type: event.type,
emailId: event.data.email_id,
tags: event.data.tags, // { flow, utm_source, utm_campaign }
occurredAt: event.occurred_at,
bounceType: event.data.bounce?.type ?? null,
});
return new Response('ok'); // answer fast; do heavy work later
}
recordEmailEvent is your own function that writes to the warehouse or analytics store. Because tags come back on every email.* event, you can now group welcome-email bounce rate by utm_source and see, for instance, whether one paid channel produces a share of signups with addresses that bounce. That is a lead-quality signal you can act on in the ad account.
Operational notes from AgentiSend's webhook documentation: read the raw body before any JSON parsing, reject timestamps far from your clock, return 2xx quickly, and deduplicate on the event id because delivery is at least once. A failed delivery is retried 10 times, then dead-lettered, and POST /webhooks/{id}/replay re-sends a range after an outage. Endpoint URLs must be https. In local development, npx @agentisend/sdk-node webhooks listen --secret whsec_… --forward-to http://localhost:3000/api/email-events forwards deliveries with their signature headers unchanged.
Step 5: test the whole loop
curl -X POST localhost:3000/api/welcome \
-H 'content-type: application/json' \
-d '{"email":"bounced@simulator.agentisend.com","userId":"u_1042","utmSource":"meta","utmCampaign":"q4-prospecting"}'
The route returns {"id":"…"}, and your events route should receive an email.bounced event with "simulated": true in data and your tags attached. Repeat with delivered@ and complained@ to check each branch of your metrics, then filter simulated events out of reporting.
AgentiSend for Next.js
Best for: Next.js teams that want retry-safe sends, events they can join to campaign data, and a lower price than Resend at every volume both sell.
AgentiSend is a transactional email API for applications and AI agents. The free plan includes 5,000 emails a month and 170 a day with no card; Starter is $9 for 30,000 and Pro $16 for 50,000. Coming from Resend, import { Resend } from 'agentisend/compat-resend' keeps your existing calls, and a webhook endpoint created with payload_format: "resend" sends the body shape your Resend handler already parses.
The full Next.js guide is at agentisend.com/docs/guides/nextjs, and accounts open at agentisend.com.
Other providers
Resend
Best for: teams already using Resend's SDK that need SOC 2 Type II on every plan.
Watch out for: the free plan is 3,000 a month at 100 a day, idempotency keys last 24 hours, and billing is monthly only.
Postmark
Best for: teams that want 45 days of activity on every plan and SMTP.
Watch out for: no idempotency key, so a double-submitted signup form can send twice unless you deduplicate yourself.
Mailgun
Best for: apps that need both an HTTP API and an SMTP endpoint, with HMAC-signed webhooks.
Watch out for: logs last 1 day on Free and Basic and 5 on Foundation.
Amazon SES
Best for: Next.js apps already deployed on AWS that want the lowest price per message.
Watch out for: new accounts start in a per-Region sandbox limited to verified recipients and 200 messages per 24 hours, with an initial response to production access within 96 hours.
Questions people ask
Can I send email from a Next.js client component? No. Send from a route handler or a Server Action so the API key never reaches the browser.
Should I use the Edge runtime? AgentiSend's tested example sets runtime = 'nodejs'. Use that unless you have checked your setup on Edge.
How do I stop a double-click sending two welcome emails? Pass an idempotency key derived from the user, such as welcome/<userId>. The second request returns the first message's id.
How do I tie email outcomes to ad campaigns? Put the campaign source in tags when you send. Tags come back on every email.* webhook event, so your warehouse can group delivery and bounce rates by source.
Sources
Documentation read 28 September to 10 November 2026: resend.com/docs/dashboard/emails/idempotency-keys, postmarkapp.com/support/article/what-is-an-idempotency-key, postmarkapp.com/developer/webhooks/webhooks-overview, documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks, docs.aws.amazon.com/ses/latest/dg/request-production-access.html. Pricing pages read 9 November 2026: resend.com/pricing, postmarkapp.com/pricing, mailgun.com/pricing, aws.amazon.com/ses/pricing.