How to Send Emails in Next.js with Mailofly
Send transactional emails, verification codes, and invoices from Next.js App Router, Route Handlers, and Server Actions in under 5 lines of code.
npm install @mailofly/nodeGet Up and Running in 3 Easy Steps
Install the Mailofly package
Run `npm install @mailofly/node` in your Next.js project root. Works seamlessly with Next.js 14, 15, and 16 with zero native C++ binding dependencies.
Add your API Key to .env.local
Create a free Mailofly account, verify your custom domain with 1-click DNS records, and add `MAILOFLY_API_KEY=mf_live_...` to `.env.local`.
Call mailofly.emails.send()
Import `Mailofly` inside any Server Action or Route Handler (`POST`). Pass `from`, `to`, `subject`, and your HTML string or React Email component.
Production-Ready Code Example
Copy and paste into your project. Fully typed and tested.
import { Mailofly } from "@mailofly/node";
import { NextResponse } from "next/server";
const mailofly = new Mailofly({
apiKey: process.env.MAILOFLY_API_KEY!,
});
export async function POST(request: Request) {
try {
const { email, name } = await request.json();
const data = await mailofly.emails.send({
from: "Acme Team <hello@yourdomain.com>",
to: [email],
subject: `Welcome to Acme, ${name}!`,
html: `
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
<h2>Welcome aboard, ${name}!</h2>
<p>Your workspace is ready. Get started right away.</p>
<a href="https://acme.com/dashboard" style="background:#000;color:#fff;padding:10px 20px;border-radius:6px;text-decoration:none;">Go to Dashboard</a>
</div>
`,
tags: [{ name: "category", value: "welcome" }],
});
return NextResponse.json({ success: true, messageId: data.id });
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}Engineered for Next.js
Zero Cold-Start Lag
Optimized for Vercel, Netlify, and Cloudflare Pages serverless runtimes. Initializing the client takes < 2ms.
React Email Native Support
Render JSX email templates into HTML strings directly using `@react-email/render` before dispatching.
Sub-100ms Execution
HTTP API requests complete within tens of milliseconds so your Next.js route handlers never stall your UI.
Explore Mailofly Infrastructure Capabilities
Build resilient, high-deliverability email systems with our core developer tools.
Frequently Asked Questions about Next.js
Start Sending from Next.js in Minutes
3,000 free emails every month. Copy your API key, run the code snippet, and watch your delivery logs in real time.