Sending Emails with React Email and Next.js
Tags: nextjs, react, javascript, opensource
Published: 2023-01-21 16:59:19

---
title: Sending Emails with React Email and Next.js
description: In this tutorial, we will learn how to create and send HTML emails with React Email and Next.js
slug: next-js-react-email-sending
published: true
canonical_url: https://kirandev.com/next-js-react-email-sending
tags: nextjs, react, javascript, opensource
---

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

## Prerequisites

- [Next.js](https://nextjs.org/)
- [React Email](https://react.email/)
- [Nodemailer](https://nodemailer.com/about/)

## Getting Started

Let's start with a new Next.js project. You can use the [Next.js CLI](https://nextjs.org/docs/api-reference/create-next-app) to create a new project.

```bash
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.

```bash
cd next-email
```

## Create Email Template

We will use the [React Email](https://react.email/) to create a new email template.

Let's install dependencies.

```bash
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.

```javascript
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.

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

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

```bash
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.

```bash
npm install nodemailer
```

```bash
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.

Find the source code on [GitHub](https://github.com/devkiran/NextAPI/blob/main/lib/server/email/sendEmail.tsx)

```js
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.

```bash
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.

```javascript
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.

---

If you're planning to build a SaaS app, then you might be interested in [NextAPI](https://github.com/devkiran/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.