
Testing email functionality locally can be tricky without sending actual emails to users. Mailtrap solves this problem by providing a secure virtual inbox for testing email flows. It allows developers to inspect email content, check HTML/CSS rendering, and validate email headers without spamming real inboxes.
If you're new to email functionality in Next.js, I recommend first reading How to Send E-Mail Using NodeMailer and React Email in Next.js. It covers setting up NodeMailer and creating React-based email templates in detail.
Update your .env file with the Mailtrap credentials:
EMAIL_HOST=smtp.mailtrap.io
EMAIL_PORT=587
EMAIL_USER=your-mailtrap-username
EMAIL_PASS=your-mailtrap-password Modify your existing server/email.ts file to use the new SMTP credentials. If you followed the setup in How to Send E-Mail Using NodeMailer and React Email in Next.js, this step will feel familiar.
"server-only";
import { render } from '@react-email/components';
import nodemailer, { Transporter } from 'nodemailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';
import { ReactElement } from 'react';
let transporter: Transporter<SMTPTransport.SentMessageInfo> | null = null;
const getTransporter = (): Transporter<SMTPTransport.SentMessageInfo> => {
if (!transporter) {
transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST as string,
port: parseInt(process.env.EMAIL_PORT as string),
secure: false,
auth: {
user: process.env.EMAIL_USER as string,
pass: process.env.EMAIL_PASS as string,
},
} as SMTPTransport.Options);
}
return transporter;
};
export const sendEmail = async ({
to,
subject,
component,
}: {
to: string;
subject: string;
component: ReactElement;
}) => {
const transport = getTransporter();
const emailHtml = await render(component);
return transport.sendMail({
from: 'noreply@yourdomain.com',
to: to,
subject: subject,
html: emailHtml,
});
}; npm run dev.If you're unfamiliar with how to trigger email functionality in Next.js, refer to How to Send E-Mail Using NodeMailer and React Email in Next.js for a guide on setting up the frontend integration.
Integrating Mailtrap into your Next.js workflow ensures a safe and efficient way to test email functionality. By simulating real-world email delivery scenarios, you can debug and validate email flows without the risk of reaching end-user inboxes.