Send emails with Next.js
Integrate YourSend into your Next.js application using API routes.
Prerequisites
- Create an API key
- Verify your domain
- A Next.js project (App Router or Pages Router)
1. Install
npm install yoursendAdd your API key to .env.local:
.env.local
YOURSEND_API_KEY=ys_live_...2. Create an API route
Create a server-side API route to send emails securely:
app/api/send/route.ts
import { YourSend } from 'yoursend';
import { NextResponse } from 'next/server';
const ys = new YourSend({ apiKey: process.env.YOURSEND_API_KEY! });
export async function POST(request: Request) {
const { to, subject, html } = await request.json();
try {
const message = await ys.send({ channel: 'email', to, subject, html });
return NextResponse.json({ message_id: message.message_id });
} catch (err) {
const error = err instanceof Error ? err.message : 'Send failed';
return NextResponse.json({ error }, { status: 400 });
}
}3. Call from the client
app/contact/page.tsx
'use client';
async function sendEmail() {
const res = await fetch('/api/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
to: 'user@example.com',
subject: 'Hello from Next.js',
html: '<p>This email was sent from a Next.js app!</p>',
}),
});
const data = await res.json();
console.log(data);
}
export default function ContactPage() {
return <button onClick={sendEmail}>Send Email</button>;
}