DEV Community

Kiran Krishnan
Kiran Krishnan

Posted on • Updated on • Originally published at kirandev.com

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
Enter fullscreen mode Exit fullscreen mode

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

cd next-email
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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",
}
Enter fullscreen mode Exit fullscreen mode

Preview Email Template

Add the following script in your package.json file.

{
  "scripts": {
    "preview-email": "email dev"
  }
}
Enter fullscreen mode Exit fullscreen mode

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

npm run preview-email
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
npm i --save-dev @types/nodemailer
Enter fullscreen mode Exit fullscreen mode

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.

Find the source code on GitHub

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,
  })
}
Enter fullscreen mode Exit fullscreen mode

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

SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM_EMAIL=
Enter fullscreen mode Exit fullscreen mode

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" })
}
Enter fullscreen mode Exit fullscreen mode

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


If you're planning to build a SaaS app, then you might be interested in NextAPI. NextAPI is a Next.js RESTful API Starter for building SaaS Apps. NextAPI can handle the heavy lifting for common SaaS features such as authentication, team management, invites, subscriptions, and more.

Top comments (3)

Collapse
 
bukinoshita profile image
Bu Kinoshita

Loved this <3

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
devkiran profile image
Kiran Krishnan

Thanks @abhaysinghr1