Sending Emails From Your React App
Published: 2024-03-11 16:38:41

by [Ejiro Thankgod](https://blog.openreplay.com/authors/ejiro-thankgod)

<blockquote><em>
How do you send emails from a React app? This article shows how to integrate the React-Email package and the Resend platform to simplify the task.
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>


Traditionally, email design has been a laborious chore, juggling HTML code and inconsistent rendering across platforms. [React-Email](https://react.email/docs/introduction) changes the game. This forward-thinking library leverages the power of React and TypeScript to offer a streamlined, component-based approach to crafting beautiful, responsive emails. With its intuitive interface and pre-built components, React-Email empowers developers to easily build emails, ensuring consistent rendering across devices and clients.

Imagine crafting personalized emails that land flawlessly in inboxes, nurturing leads, and driving conversions. [Resend](https://resend.com/docs/introduction), the next-generation email platform, unlocks this magic. Say goodbye to spam folders and hello to automated workflows, powerful analytics, and an intuitive interface that empowers you to design irresistible email experiences. Resend transforms email from a chore to a strategic weapon, propelling your business forward.

The combination of both [React-Email](https://react.email/docs/introduction) and [Resend](https://resend.com/docs/introduction) helps developers build captivating email templates that seamlessly send transactional emails and forge genuine connections with their audience. Leverage advanced automation, dynamic content, and data-driven insights to deliver relevant, timely emails that resonate with your recipients. Simplifying React-Email integration with Resend transforms email marketing into relationship building, driving engagement and growth for any brand.

## Getting Started With React-Email
Use `create-next-app` to launch a new Next.js application, as it takes care of your setup. To start a project, execute:
```bash
npx create-next-app@latest
```
You'll notice the following prompts during installation:

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706350854201_Screenshot+2024-01-27+at+11.20.25.png)

*N/B: Will be using Pages Router instead of App Router.*
After this, the Next App will be created with the project name.

### Customizing Email With React-Email
There are two methods for customizing email with React-Email i.e:
- The Automatic Setup
- The Manual Setup
 
But we’ll proceed with the manual setup since we already have our Next app running. The manual setup sits well with integration compared to the automatic setup. So, we’ll start by installing some components for the setup.

## Install Dependencies

 Install a few components and the React Email package locally.
```bash
npm install react-email @react-email/components -E
```
## Add the Script

 Add the script below to your package.JSON file.
```json
{
  "scripts": {
    "dev": "email dev"
  }
}
```

### Create the Template
 Create a new folder called `emails` in the root of your Next App, create a new file inside called `index.tsx`, and add the following code:
 
```typescript
import { Button, Html } from "@react-email/components";
import * as React from "react";

export default function Email() {
  return (
    <Html>
      <Button
        href="https://example.com"
        style={{ background: "#000", color: "#fff", padding: "12px 20px" }}
      >
        Click me
      </Button>
    </Html>
  );
}
```

Launch the development server:

```bash
npm run dev
```

To see the changes, go to `localhost:3000` and modify index.tsx.

![image](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/image1.png)

From here, you can create, modify, and design the email template however you see fit, but React-Email has provided us with some example templates to choose from for this tutorial.

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706352734384_Screenshot+2024-01-27+at+11.51.56.png)

So from here, we’ll modify our template to our taste, just like the example below, before integrating Resend API for easy communication.

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706362984748_Screenshot+2024-01-27+at+14.41.46.png)

## Integration with Resend
Resend is an email marketing platform that helps businesses design, automate, and send targeted email campaigns. It offers a variety of features to help you create effective email marketing campaigns, including:

- Drag-and-drop email builder: You can easily create beautiful and responsive emails without writing any code.
- Email automation: Automate your email marketing with workflows that trigger emails based on specific events, such as when someone signs up for your newsletter or abandons their cart.
- Personalization: Use dynamic content and segmentation to send personalized emails relevant to your subscribers.
- Analytics: Track your email marketing results with detailed reports showing your campaigns' performance.
- Deliverability: Resend has a high deliverability rate, so you can be sure your emails reach your subscribers' inboxes.

By integrating Resend with React-Emails, we can send targeted emails, personalize our emails, and track emails from the point of creation to the point of receiving them.

### Prerequisite
If your Next App is ready, we'll need to create an account, an API key, and a domain on the Resend platform.

Firstly, we need to create an account with Resend to gain access to their platform. Although they’re a paid platform, they also have a free package. 

![image](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/image2.png)

You can sign up with either *Github or Google* or click the *Create Account* button. After creating an account, you’ll create an API key to initiate the Resend API.

![image](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/image3.png)

To create the API key, input the name, select *Full access or Sending access*, and select the domain. If you don’t have one, just click on *Add*, and the key is created.

You can create a domain that helps you send emails from any email address,  although it’s free for one domain with limited features that you can upgrade to its full potential.

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706356340952_Screenshot+2024-01-27+at+12.52.08.png)

### Install Dependencies
Let’s start by installing some dependencies for the integration. Install the Resend Node.JS SDK dependency.
```bash
npm install resend
```
### Create Email Template
Modify the code base in the `emails` folder at the root of our Next app with the redesigned Slack email template from the initial Slack template.

```typescript
/emails/index.ts;
import {
  Body,
  Container,
  Column,
  Head,
  Heading,
  Html,
  Img,
  Link,
  Preview,
  Row,
  Section,
  Text,
} from "@react-email/components";
import * as React from "react";

interface SkyConfirmEmailProps {
  validationCode?: string;
}

const baseUrl = process.env.VERCEL_URL
  ? `https://${process.env.VERCEL_URL}`
  : "";

export const SkyConfirmEmail = ({ validationCode }: SkyConfirmEmailProps) => (
  <Html>
    <Head />
    <Preview>Confirm your email address</Preview>
    <Body style={main}>
      <Container style={container}>
        <Section style={logoContainer}>
          <Img
            src={`https://img.design-vector_343694-2506.jpg`}
            width="120"
            height="90"
            alt="Sky"
          />
        </Section>
        <Heading style={h1}>Confirm your email address</Heading>
        <Text style={heroText}>
          Welcome to Sky Ejiro. Your confirmation code is below - enter it in
          your open browser window, and we'll help you get signed in.
        </Text>

        <Section style={codeBox}>
          <Text style={confirmationCodeText}>{validationCode}</Text>
        </Section>

        <Text style={text}>
          If you didn't request this email, there's nothing to worry about; you
          can safely ignore it.
        </Text>

        <Section>
          <Row style={footerLogos}>
            <Column style={{ width: "66%" }}>
              <Img
                src={`https://img.freepik.com/free-vector/bird-colorful-gradient-design-vector_343694-2506.jpg`}
                width="120"
                height="70"
                alt="Sky"
              />
            </Column>
            <Column>
              <Section>
                <Row>
                  <Column>
                    <Link href="/">
                      <Img
                        src={`https://img.twitter-x-logo-official.jpg`}
                        width="42"
                        height="42"
                        alt="Sky"
                        style={socialMediaIcon}
                      />
                    </Link>
                  </Column>
                  <Column>
                    <Link href="/">
                      <Img
                        src={`https://upload.Facebook_Logo_2023.png`}
                        width="38"
                        height="38"
                        alt="Sky"
                        style={socialMediaIcon}
                      />
                    </Link>
                  </Column>
                  <Column>
                    <Link href="/">
                      <Img
                        src={`https://upload.LinkedIn_icon_circle.svg.png`}
                        width="40"
                        height="40"
                        alt="Sky"
                        style={socialMediaIcon}
                      />
                    </Link>
                  </Column>
                </Row>
              </Section>
            </Column>
          </Row>
        </Section>

        <Section>
          <Link
            style={footerLink}
            href="https://skyhq.com"
            target="_blank"
            rel="noopener noreferrer"
          >
            Our blog
          </Link>
          &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
          <Link
            style={footerLink}
            href="https://sky.com/legal"
            target="_blank"
            rel="noopener noreferrer"
          >
            Policies
          </Link>
          &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
          <Link
            style={footerLink}
            href="https://sky.com/help"
            target="_blank"
            rel="noopener noreferrer"
          >
            Help center
          </Link>
          &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
          <Link
            style={footerLink}
            href="https://sky.com/community"
            target="_blank"
            rel="noopener noreferrer"
            data-auth="NotApplicable"
            data-linkindex="6"
          >
            Sky Community
          </Link>
          <Text style={footerText}>
            ©2024 Sky Technologies, LLC, a Salesforce company. <br />
            5990 Howard Street, San Francisco, CA 941076, USA <br />
            <br />
            All rights reserved.
          </Text>
        </Section>
      </Container>
    </Body>
  </Html>
);

SkyConfirmEmail.PreviewProps = {
  validationCode: "DJZ-ABC",
} as SkyConfirmEmailProps;

export default SkyConfirmEmail;
```

Create a `.env` file in the root folder of the Next app, copy the generated API Key, and paste it into the `.env` file. 
```
RESEND_API_KEY="Generated API Key here!!!"
```


<CTA_Middle_Frameworks />



### Send Email With React Parameter
If using the Pages Router, create an API file in `pages/api/send.ts`.
Import the React email template, then send an email with the React argument.
```typescript
/pages/api/send.ts;

import { SkyConfirmEmail } from "../../emails/sky-confirm";
import type { NextApiRequest, NextApiResponse } from "next";
import { Resend } from "resend";

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

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { data, error } = await resend.emails.send({
    from: "Sky <onboarding@resend.dev>",
    to: ["ejirouweghrepha@gmail.com"],
    subject: "Welcome to Sky Ejiro!",
    react: SkyConfirmEmail({ firstName: "John" }),
  });

  if (error) {
    return res.status(400).json(error);
  }

  res.status(200).json({ message: "Email sent successfully!" });
};
```
    
The code above sets up a Next.js API endpoint that, when called, uses the Resend service to send a confirmation email with the specified template and handles the response accordingly.

### Modify Script
Modify the `"dev": "email dev"` script to `"email": "email dev"`  below in the `package.json` file.

```json
"scripts": {
        "email": "email dev",
      },
```

Launch the development server for both Next and React-Email.
```bash
npm run dev // For Next app to run on http://localhost:3000
    
npm run email // For react-email to run on http://localhost:3001
```
*Note: After running the first server on `http://localhost:3000`, open another terminal, and run a second server, you’ll be prompted to initiate a port on `http://localhost:3001` since the Next App uses the first port.*

If we route to `localhost:30001/api/send`, we’ll automatically initiate the POST request, which sends our message “Email sent Successfully!”

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706425966411_Screenshot+2024-01-27+at+13.56.18.png)

Likewise, we get a successful message if we use Postman to send a post request.

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706426333557_Screenshot+2024-01-28+at+08.18.33.png)

After which, if we move to our mailbox, we’ll see a confirmation mail as we have designed.

![-](https://blog.openreplay.com/images/sending-emails-from-your-react-app/images/s_2BC43D8E5B95770463DABE9B5ABFC37BD7A8AA18B9C97FC61945D7C0B636CA15_1706363004144_Screenshot+2024-01-27+at+14.42.17.png)

## Conclusion
Integrating Resend with React-Email into your Next project allows you to compose emails more efficiently and effectively, as you are no longer limited to utilizing rigid templates and encountering inconsistent rendering. With the combination of React-Email and Resend, you can now design dynamic, visually stunning emails that captivate audiences and drive results. This powerful partnership paves the way for a future where email development is as intuitive and enjoyable as any other UI, pushing the boundaries of engagement and driving your business forward.

Resources
- [Nextjs](https://nextjs.org/docs/getting-started/installation)
- [React-Email](https://react.email/docs/introduction)
- [Resend](https://resend.com/docs/introduction)
- [Postman](https://web.postman.co/)
- [GitHub](https://github.com/EJINEROZ/Resend-React-Email-Integration)