DEV Community

Cover image for How to Create and Send Custom Emails using React Email and Resend API
The ERIN
The ERIN

Posted on • Edited on

How to Create and Send Custom Emails using React Email and Resend API

Frontend developers often face challenges when sending custom emails directly from their applications. This process required complex backend setups and specialized knowledge, making it difficult for beginners to handle. However, thanks to Next.js and user-friendly APIs such as the React Email and Resend API, creating and sending personalized emails has become much more straightforward.

In this beginner-friendly guide, you'll explore using React Email and the Resend API to craft and send customized emails effortlessly. This way, you can easily communicate with your users in a more tailored and personalized manner. Let's dive in and discover the exciting possibilities of email customization with React and the Resend API!

 

Prerequisites

To follow through with this tutorial, you need the following:

  • Basic knowledge of TypeScript and its syntax

  • Basic understanding of Next.js.

  • npm installed on your computer. You can get it here if you don’t have npm installed on your computer.

  • A Resend account. You can create a free account by clicking here.

 

Setting up the Development Environment

To start creating and sending custom emails using React Email and Resend API, you have to set up a new Next.js project with TypeScript. Next.js is a popular React framework that offers server-side rendering and other powerful features for building modern web applications. TypeScript, on the other hand, provides static typing to your JavaScript code, enhancing code quality and productivity.

 

Creating a Next.js Project

To create a new Next.js project with TypeScript, follow these steps:

  • Open your terminal or command prompt and run the following command:


npx create-next-app@latest



Enter fullscreen mode Exit fullscreen mode

Next, you will be prompted to give your project a name. Also, choose TypeScript as your preferred language. You can use the new App Router folder or the srcdirectory. You should choose the App Router as your root directory for this article.

  • After the prompts, create-next-app will create a folder with your project name and install the required dependencies.

With your Next.js project set up, the next step is to install the necessary dependencies for working with React Email and Resend API. These libraries will let you create custom email templates and handle email sending efficiently.

 

Installing React Email and Resend Dependencies

To install react email package locally with a few components in your project.

  • Run the following command in your terminal:


npm install react-email @react-email/button @react-email/html @react-email/components


Enter fullscreen mode Exit fullscreen mode
  • Add the following script to your package.json


{
  "scripts": {
    "dev": "email dev --dir app/emails"
  }
}


Enter fullscreen mode Exit fullscreen mode

This script starts a local development server and will watch your files located in the app/emails directory and automatically rebuild your email when you make changes.

Next, you have to install the Resend API to your project. To do this, run the following command in your terminal.



npm install resend



Enter fullscreen mode Exit fullscreen mode

Once all the installations are complete, your project will have the necessary tools for this article.

In the following sections, you will learn how to design engaging email templates and implement the email-sending functionality with React Email and Resend API.

 

Creating and Designing the Email Template Component

In this section, you’ll create a personalized email template component containing your email templates.

  • Create an' email' folder in your app directory. Inside the folder, create a new file called Subscribe.tsx. This file will contain the structure of your email template.

  • Copy the following code snippet and add it to your file.



import {
  Body,
  Container,
  Head,
  Html,
  Preview,
  Section,
  Text,
} from "@react-email/components";
import * as React from "react";

interface SubscribeEmailProps {
  name?: string;
  email?: string;
}

export const SubscribeEmail = ({name, email}: SubscribeEmailProps) => {
  return (
    <Html>
      <Head />
      <Preview>Dropbox reset your password</Preview>
      <Body style={main}>
        <Container style={container}>
          <Section>
            <Text style={text}>Hi {name},</Text>
            <Text style={text}>
              Thank you for subscribing to our Newsletter. Your {email} has been added to our mailing list
            </Text>
            <Text style={text}>
              Our Bi-weekly newsletter will always be in your inbox with all.
              Major Announcements, Special Offers, and much more exciting
              things. We won't spam your mailbox. See you soon!
            </Text>
            <Text style={text}>
              If you've got any other questions, please don&apos;t hesitate to
              contact Us via our Help Center for more help.
            </Text>
            <Text style={text}> Thank you. Happy Coding!</Text>
          </Section>
        </Container>
      </Body>
    </Html>
  );
};

export default SubscribeEmail;

const main = {
  backgroundColor: "#f6f9fc",
  padding: "10px 0",
};

const container = {
  backgroundColor: "#ffffff",
  border: "1px solid #f0f0f0",
  padding: "45px",
};

const text = {
  fontSize: "16px",
  fontFamily:
    "'Open Sans', 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif",
  fontWeight: "300",
  color: "#404040",
  lineHeight: "26px",
};

const button = {
  backgroundColor: "#007ee6",
  borderRadius: "4px",
  color: "#fff",
  fontFamily: "'Open Sans', 'Helvetica Neue', Arial",
  fontSize: "15px",
  textDecoration: "none",
  textAlign: "center" as const,
  display: "block",
  width: "210px",
  padding: "14px 7px",
};

const anchor = {
  textDecoration: "underline",
};



Enter fullscreen mode Exit fullscreen mode

Let's break down the code snippet to understand how it crafts a visually appealing and informative email.

The import statement starts by importing Body, Container, Head, Html, Preview, Section, and Text components from the @react-email/components library. These components are essential building blocks the @react-email/components library provides to create and design email templates using React.

Following the imports, the code defines an interface named SubscribeEmailProps. The interface specifies the prop types that can be passed to the SubscribeEmail component. In this case, the interface includes two optional properties: name of type string and email of type string. The nameand email props are marked as optional by using the ? symbol after their names means they can be provided or left undefined.

Finally, the email has an inline CSS style for various elements.

  • To preview your email template, start a development server. Open up your terminal and run the following command:


npm run email


Enter fullscreen mode Exit fullscreen mode

This will install additional dependencies to help set up the development environment. Once installed, head to https://localhost:3000 to preview your email template.

 

NOTE: You might get a “failed to start server” error message like this below. To resolve this issue, ensure no application is running on https://localhost:3000 on your machine. Once you have terminated the application, rerun the npm run email command. Your application should be running on the development server now.

 

This is an error message you might face when you run your development server

After rerunning the development command, your environment will look like the image below. From the development server, you can inspect the source code of the template, and you can also preview all other email templates you have created.

 

This preview how the development server will look after starting the development server

react-email has pre-built components that are traditionally inside an email template for you to build customized and personalized templates. It also has a Tailwind component that lets you use tailwind classes.

Different examples are available for you to explore from other templates you might have seen of some popular services or brands like Airbnb, Nike, Notion, and many more. Check out their examples page to explore more editable email template designs.

 

Configuring the Resend API from the Server-Side

Now that your email template is ready, you can integrate the Resend API with the react-email package and send emails conveniently. react-email is compatible with integrations like Nodemailer, SendGrid, Postmark, AWS SES, and many more. Resend is the creator of react-email, and it provides easy to setup integration options with the react-email package.

To get started,

  • Log in to your Resend account to get your API Key. Click on API keys from the sidebar. Create a new API key on the API keys page by clicking the “Create API Key” button.

Give your API key a name, choose the full access option for the Permissions input, and click the Add button to generate an API Key.

Note: You can only copy your secret key once after generating it, so save it somewhere on your computer. If lost, you can always generate a new API key.

  • In the root directory of your project, create a new file called .env. Inside the .env file, define your environment variable with the key-value pair. For example,


RESEND_API_KEY=your_openai_api_key_here



Enter fullscreen mode Exit fullscreen mode

Save the .env file. Note that you should replace your_openai_api_key_here with your actual OpenAI API key.

  • Next, create a folder called api inside your app directory. Inside the api folder, create another folder called email and then a file named route.ts. route.tswill contain the logic to the code that lets you directly send emails to your user's emails.

  • Add the following code snippet to the route.ts file.



import { Resend } from "resend";
import SubscribeEmail from "@/app/emails/subscribe";
import { NextResponse } from "next/server";

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(request: Request) {
  const { name, email } = await request.json();

  await resend.sendEmail({
    from: "onboarding@resend.dev",
    to: email,
    subject: "Thank you for Subscribing to our Newsletter",
    react: SubscribeEmail({
      name,
      email,
    }),
  });

  return NextResponse.json({
    status: "OK",
  });
}



Enter fullscreen mode Exit fullscreen mode

This code snippet is a serverless function. Its purpose is to handle incoming POST requests and send a custom email to the subscriber using the Resend API.

It starts by importing the necessary modules: Resend from the resend library, SubscribeEmail from the @/app/emails/subscribe file (representing the custom email template), and NextResponse from next/server (used to return responses from the Next.js serverless function).

It then creates a new instance of the Resend class by passing the RESEND_API_KEY stored in the environment variable. This step sets up the Resend API client, allowing communication with the Resend service for sending emails.

It defines an asynchronous function that takes a request object as its parameter. This function will handle incoming POST requests. Within the function, the incoming request body is parsed using await request.json().

The resend.sendEmail method sends the custom email to the subscriber. It takes an object as an argument with the following properties:

from: The email address from which the email will be sent.
to: The recipient's email address.

subject: The subject of the email.

react: The email's content is generated by calling the SubscribeEmail component and passing the name and email values.

After sending the email, the function returns a JSON response using NextResponse.json with the status set to OK.

 

NOTE: You need a valid email address as your value to the from key to send your emails properly.
Resend provides an email address(onboarding@resend.dev) for the development environment. You do not want to use this email in your production environment due to performance issues, and Resend not supporting the email address for the production environment. Instead, connect your domain to your Resend account, and include the email address as your value to the from key.

 

In the next section, you will learn how to integrate the Resend API into your web forms and initiate the email-sending functionality.

 

Integrating Resend API to Send Custom Emails from the Client Side

In this section, you will integrate the Resend API into a form to enable seamless email communication with your users. To get started:

  • Add the following code snippet to your page.tsx file:


"use client";

import React, { useState } from "react";


const ContactForm = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleChange = (e) => {
    setName(e.target.value);
  };

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    await fetch("/api/email", {
      method: "POST",
      body: JSON.stringify({
        name,
        email,
      }),
    });
  };
  return (
    <>

        <h2>Subscribe to our Newsletter</h2>


        <div>
          <p>Name</p>
          <input
            type="text"
            name="name"
            id="name"
            value={name}
            onChange={handleChange}
          />
        </div>
        <div>
          <p>Email</p>
          <input
            type="email"
            name="email"
            id="email"
            value={email}
            onChange={handleEmailChange}
          />
        </div>

      <button type="submit" onClick={handleSubmit}>
        Subscribe
      </button>
    </>
  );
};

export default ContactForm;


Enter fullscreen mode Exit fullscreen mode

This code snippet implements a contact form for subscribing to a newsletter. It utilizes React's state management with useState to capture and update the user's name and email input. The form triggers an asynchronous handleSubmit function when clicking the Subscribe button.

Within this function, the form data (name and email) is sent to the backend server using the fetch API as a POST request to the /api/email endpoint. This allows the server to handle email sending with the Resend API, facilitating efficient communication with users.

The ContactForm component is designed to provide an intuitive user experience for subscribing to the newsletter, enhancing email communication with potential subscribers.

Start your client-side development server and preview your web application at https://localhost:3001. As I highlighted in the “Configuring the Resend API from the Server-Side“ section, Don’t use the resend onboarding email “onboarding@resend.dev” during production; instead, connect your domain to your Resend account to avoid email-sending performance issues.

 

Conclusion

In conclusion, this article has demonstrated the seamless integration of React Email and Resend API to create and send custom emails with personalised content. You started by setting up a Next.js project with TypeScript, utilizing React Email's components to design captivating email templates. You then used the Resend API to deliver the custom emails to subscribers efficiently.

Following the steps outlined in this tutorial, you have acquired the foundational knowledge to elevate your email communication and engage your audience effectively. However, the capabilities of React Email and Resend API extend beyond what was covered here.

As you continue your journey, explore more advanced React Email and Resend API features, such as email tracking, email analytics, and automated email campaigns. By harnessing the full potential of these tools, you can create immersive email experiences that leave a lasting impact on your users.

Happy Coding!

Top comments (2)

Collapse
 
phemehboy profile image
okunade femi joel

Please how do I configure my base URL so that I can link to my file locally. Need it for my links and images in react mail template

Collapse
 
johnuchendu profile image
John Uchendu

Kindly review because somethings have changed