Sending Emails with React Email and Next.js

In this tutorial, we will learn how to create and send HTML emails with React Email and Next.js

Prerequisites

Getting Started

Let's start with a new Next.js project. You can use the Next.js CLI to create a new project.

npx create-next-app next-email --ts

Wait for the project to be created. Once the project is created, let's move into the project directory.

cd next-email

Create Email Template

We will use the React Email to create a new email template.

Let's install dependencies.

npm install react-email @react-email/html @react-email/text @react-email/section @react-email/container -E

Now, let's create a new email template using the React Email components. This is a simple React component that will be converted to HTML email template.

We will create a new file emails/WelcomeTemplate.tsx and add the following code.

import { Html } from "@react-email/html";
import { Text } from "@react-email/text";
import { Section } from "@react-email/section";
import { Container } from "@react-email/container";

export default function WelcomeEmail() {
  return (
    <Html>
      <Section style={main}>
        <Container style={container}>
          <Text style={heading}>Hi there!</Text>
          <Text style={paragraph}>Welcome to our app!</Text>
        </Container>
      </Section>
    </Html>
  );
}

// Styles for the email template
const main = {
  backgroundColor: "#ffffff",
};

const container = {
  margin: "0 auto",
  padding: "20px 0 48px",
  width: "580px",
};

const heading = {
  fontSize: "32px",
  lineHeight: "1.3",
  fontWeight: "700",
  color: "#484848",
};

const paragraph = {
  fontSize: "18px",
  lineHeight: "1.4",
  color: "#484848",
};

Preview Email Template

Add the following script in your package.json file.

{
  "scripts": {
    "preview-email": "email dev"
  }
}

Now, you can preview your email template by running the following command.

npm run preview-email

This will start a local server and open your email template in the browser.

Send Email with Nodemailer

Let's install Nodemailer.

npm install nodemailer
npm i --save-dev @types/nodemailer

Create a new helper file lib/email.ts and add the following code. This will take care of sending emails using Nodemailer and the SMTP server.

import nodemailer from "nodemailer"

type EmailPayload = {
  to: string
  subject: string
  html: string
}

// Replace with your SMTP credentials
const smtpOptions = {
  host: process.env.SMTP_HOST || "smtp.mailtrap.io",
  port: parseInt(process.env.SMTP_PORT || "2525"),
  secure: false,
  auth: {
    user: process.env.SMTP_USER || "user",
    pass: process.env.SMTP_PASSWORD || "password",
  },
}

export const sendEmail = async (data: EmailPayload) => {
  const transporter = nodemailer.createTransport({
    ...smtpOptions,
  })

  return await transporter.sendMail({
    from: process.env.SMTP_FROM_EMAIL,
    ...data,
  })
}

Make sure your .env file contains the following environment variables.

SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM_EMAIL=

Now, let's create a new file pages/api/send-email.ts and add the following code.

import type { NextApiRequest, NextApiResponse } from "next";
import { render } from "@react-email/render";
import WelcomeTemplate from "../../emails/WelcomeTemplate";
import { sendEmail } from "../../lib/email";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await sendEmail({
    to: "kiran@example.com",
    subject: "Welcome to NextAPI",
    html: render(WelcomeTemplate()),
  });

  return res.status(200).json({ message: "Email sent successfully" });
}

Now you can visit http://localhost:3000/api/send-email to send the email.