Next.js
Send transactional email from Next.js API routes and Server Actions.
Installation
bash
npm install mailsetuAPI Route (App Router)
Create app/api/send-welcome/route.ts:
typescript
import { NextResponse } from 'next/server'
import MailSetu from 'mailsetu'
const client = new MailSetu(process.env.MAILSETU_API_KEY!)
export async function POST(request: Request) {
const { email, name } = await request.json()
const { id } = await client.emails.send({
from: 'Acme <noreply@acme.co>',
to: [email],
subject: `Welcome, ${name}!`,
html: `<h1>Hi ${name},</h1><p>Thanks for signing up!</p>`,
})
return NextResponse.json({ emailId: id })
}Server Action
Use directly in a Server Action:
typescript
'use server'
import MailSetu from 'mailsetu'
const client = new MailSetu(process.env.MAILSETU_API_KEY!)
export async function sendWelcomeEmail(email: string, name: string) {
return await client.emails.send({
from: 'Acme <noreply@acme.co>',
to: [email],
subject: `Welcome, ${name}!`,
html: `<h1>Hi ${name}!</h1><p>Welcome to our platform.</p>`,
})
}Environment variables
Add to .env:
bash
# .env
MAILSETU_API_KEY=ms_test_xxxxxxxx # for development
# MAILSETU_API_KEY=ms_live_xxxxxxxx # for productionWith React Email
Use React Email to build beautiful HTML emails:
typescript
import { render } from '@react-email/render'
import WelcomeEmail from '@/emails/WelcomeEmail'
import MailSetu from 'mailsetu'
const client = new MailSetu(process.env.MAILSETU_API_KEY!)
export async function sendWelcome(email: string, name: string) {
const html = render(<WelcomeEmail name={name} />)
return await client.emails.send({
from: 'Acme <noreply@acme.co>',
to: [email],
subject: `Welcome, ${name}!`,
html,
})
}