Send
Send a predefined email
Send emails using Next.js and the MailChannels Node.js SDK.
Add the mailchannels-sdk package dependency to your Next.js project.
npm i mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdkbun add mailchannels-sdkdeno add npm:mailchannels-sdkAdd your MailChannels API key to your .env file.
MAILCHANNELS_API_KEY=your-api-keyRegister an App route handler under app/api/emails/send/route.ts or a Pages API route under pages/api/emails/send.ts.
Use the html property to send an email with HTML content.
import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels(process.env.MAILCHANNELS_API_KEY)
export async function POST () {
const { data, error } = await mailchannels.emails.send({
from: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
if (error) {
return Response.json(error, {
status: error.statusCode || 500
})
}
return Response.json(data)
}import type { NextApiRequest, NextApiResponse } from 'next'
import { MailChannels } from 'mailchannels-sdk'
const mailchannels = new MailChannels(process.env.MAILCHANNELS_API_KEY)
export default async function handler (req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST')
return res.status(405).json({ error: 'Method Not Allowed' })
}
const { data, error } = await mailchannels.emails.send({
from: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
if (error) {
return res.status(error.statusCode || 500).json({ error })
}
return res.status(200).json(data)
}Create a form in your Next.js app to call the send API route.
'use client'
import { useState } from 'react'
import type { EmailsSendResponse } from 'mailchannels-sdk';
export default function SendEmail () {
const [loading, setLoading] = useState(false)
const [result, setResult] = useState<EmailsSendResponse['data']>()
async function sendEmail (e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
setLoading(true)
const response = await fetch('/api/emails/send', {
method: 'POST'
})
const data = await response.json()
setResult(data)
setLoading(false)
}
return (
<>
<h1>Send a predefined email</h1>
<form className="form" onSubmit={sendEmail}>
<button type="submit" disabled={loading}>
{loading ? 'Sending...' : 'Send Email'}
</button>
</form>
{result ? <pre>{JSON.stringify(result, null, 2)}</pre> : null}
</>
)
}Send a predefined email
Queue a predefined email
Send an email using a form
Send an email with an attachment using a form
Send an email using a template engine with a form
Perform a DKIM, SPF & Domain Lockdown Check
Create a webhook
Handle webhook events