Resend is a platform for efficient email sending that guarantees direct delivery to your inbox instead of the spam folder. Resend has different SDKs for various programming languages, including PHP, Ruby, JavaScript, Go, Python, and Elixir. Resend also supports serverless and SMTP for sending emails.
React Email is an open-source component library created by the same team behind Resend. This library can be used to create different kinds of modern, responsive email templates.
Features of Resend
- With Resend, you can send emails using various programming languages such as Python, Ruby, Go, Elixir, PHP, and JavaScript.
- Sending emails from verified DNS (Domain Name System) records.
- User-friendly dashboard that shows the status of your emails whether they have been delivered, sent, or bounced.
- View email messages directly inside the dashboard.
In this tutorial, you will learn how to send emails from a verified domain using React-Email, Next.js, and Resend.
Prerequisites
Here are what you need to follow along in this tutorial:
- Node.js installed on your machine.
- A free Resend account (sign up with Resend for free).
- A GitHub account.
Getting started with Resend
To get started with Resend, create an account by visiting resend.com. You can sign up with your email address or a GitHub account.
Make sure you confirm your account by clicking the Confirm Account button in the email you received after signing up with an email. After that, you be will redirected to your Resend dashboard.
The next step is to create an API key by following the steps below:
- Navigate to the API Keys section on the left side of your dashboard.
- Click on the Create API Key button on the right-hand side of the page.
- A modal window containing a form appears. Choose a name for the API Key Name and click on the Add button.
The API key will be generated for you once you click the Add button. You will be using this API key later on, so make a note of it.
Verifying the domain for sending emails
The domain that will be used for sending emails must be verified.
On the left-hand side of your dashboard, select Domains and click on the Add Domain button:
A new page appears. Add a domain by entering it in the input field. Then click on the Add button.
Now that you have added a domain, the next step is to add a Domain Name System (DNS) record.
Adding DNS records
To add DNS records, place your mouse over the DNS Records below the alert notification. You will observe a clipboard icon enabling you to copy the values for each listed item. You can then click on the DNS Provider on your dashboard.
💡 The DNS provider can be Namecheap, GoDaddy, Hostinger, etc.
You will be redirected to the DNS provider page where you’ll add DNS records. Add all DNS records you copied from your Resend dashboard. Then click on the Add button.
Next, navigate back to your Resend dashboard and click the Verify DNS Records button.
After that, your dashboard status will change from “Not Started” to “Pending”. This indicates the DNS records verification is in progress. You will get an email notification once the verification is completed.
Upon successful verification, your dashboard status will change to “Verified”. Now you can send emails from your verified domain.
Setting up Resend in a Next.js project
To set up Resend in a Next.js project, click here to generate the starter files based on an existing template repo. Run the command below to clone this project:
git clone <repo-git-url-provided-above>
Navigate into the project directory by running:
cd react-email-demo
Next, install dependencies by running the following command in your project’s terminal:
yarn install
On completion, run yarn run dev
in your terminal and navigate to localhost:3000 in your web browser. You should see the starter UI:
Now that you have a Next.js project running successfully, create the .env.local
file in the root of your project. Add the Resend API key that was generated for you into this file.
RESEND_API_KEY=YOUR_RESEND_API_KEY
Form component
In the components
directory, update the ContactUsForm.tsx
file by adding the following code:
// components/ContactUsForm.tsx
'use client';
import { useForm } from 'react-hook-form';
import { toast } from 'react-hot-toast'; // updated code
type FormInput = {
name: string;
email: string;
message: string;
};
export default function ContactUsForm() {
const {
register,
handleSubmit,
formState: { isSubmitting },
reset,
} = useForm<FormInput>();
/**
* The function sends a POST request to a server with form data and displays a success notification.
* @param {FormInput} formData - The formData parameter is an object that contains the input values
* from the form.
*/
async function onSubmit(formData: FormInput) {
await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: formData.name,
email: formData.email,
message: formData.message,
}),
}).then(() => {
// Toast notification
toast.success('Your email message has been sent successfully');
});
reset();
}
return (
<div className='w-10/12 md:w-6/12'>
<form
onSubmit={handleSubmit(onSubmit)} // updated code
className='mb-10 mt-5 flex w-full flex-col rounded-md bg-white p-5 py-14 shadow-lg md:max-w-3xl md:px-10 mx-auto'
>
<input
className='mt-4 mb-3 h-14 block w-full rounded-md border px-3 text-gray-600 outline-none focus:border-stone-500 focus:outline-none md:mb-0'
type='text'
placeholder='Name'
required
{...register('name')}
/>
<input
className='mt-4 mb-3 h-14 block w-full rounded-md border px-3 text-gray-600 outline-none focus:border-stone-500 focus:outline-none md:mb-0'
type='email'
placeholder='Email'
required
{...register('email')}
/>
<textarea
className='mt-4 mb-5 block w-full rounded-md border px-3 text-gray-600 outline-none focus:border-stone-500 focus:outline-none md:mb-0'
placeholder='Message Us'
rows={6}
required
{...register('message')}
/>
<button
disabled={isSubmitting}
type='submit'
className='bg-blue-700 px-6 py-3 disabled:bg-gray-500 block-primary rounded-md cursor-pointer text-white mt-4 font-bold'
>
Book Appointment
</button>
</form>
</div>
);
}
Here, you did the following:
Imported
useForm
hook from thereact-hook-form
library to handle form state and submission.Imported
toast
from thereact-hot-toast
library that displays a notification after an email message has been sent successfully.An async function named
onSubmit
is defined to handle form submission when the user submits the form. Inside this function, an API request is made using the fetch method that sends a POST request to the/api/send
endpoint with the form data as JSON in the request body.The
reset
function provided byuseForm
is used to reset the form fields after submission.
Implementing a dynamic email template
With React Email, creating a modern email template becomes very easy. According to the React Email website, there is a set of standard components to help you build amazing emails without having to deal with the mess of creating table-based layouts and maintaining archaic markup.
To use this set of standard components for building an email template, navigate to the components
directory and create the EmailMessage.tsx
file. Add the following code to this file:
// components/EmailMessage.tsx
import {
Body,
Container,
Head,
Heading,
Hr,
Html,
Preview,
Tailwind,
Text,
} from '@react-email/components';
import * as React from 'react';
type MessageUsEmailProps = {
name: string;
email: string;
message: string;
};
const MessageUsEmail = ({ name, email, message }: MessageUsEmailProps) => {
const previewText = `Weekly Updates 🚀${name} sent you a message.`;
return (
<Html>
<Head />
<Preview>{previewText}</Preview>
<Tailwind>
<Body className='bg-white my-auto mx-auto font-sans'>
<Container className='my-[20px] mx-auto p-[20px] max-w-4xl'>
<Heading className='text-black text-[20px] font-normal text-left'>
<strong>Hello {name},</strong>
</Heading>
<Text className='text-black text-[14px] leading-[24px]'>
{message}
</Text>
<Hr className='my-[16px] mx-0 w-full' />
<Text className='text-[#666666] text-[12px]'>
In a world where every email matters, Resend empowers you to send emails that captivate, engage, and convert. It's more than just an email platform; it's a catalyst for modernizing your email communication.
Don't settle for outdated email practices. Embrace the future of email communication with Resend and watch your messages soar to new heights.
</Text>
<Text className='text-[#666666] text-[12px]'>
This email is delivered to you through the Resend SDK
integrations.✨
</Text>
</Container>
</Body>
</Tailwind>
</Html>
);
};
export default MessageUsEmail;
Here, you did the following:
- Imported from
@react-email/components
to structure the email template with specific elements for email rendering. - The component receives
name
,email
, andmessage
as props of typeMessageUsEmailProps
. - The
Head
component is used for including meta information within the email's<head>
section. - The
Preview
component is used to define the text that appears in the email client's preview pane. - The
Tailwind
component is used to apply Tailwind CSS classes to style the email template.
Sending emails using the Resend SDK
So far, you have verified a domain, set up Resend in a Next.js project, and implemented a dynamic email template. It’s time to send emails using Resend.
In the app
directory, create the api/send/route.ts
file and add the following code snippet to this file:
// app/api/send/route.ts
import { Resend } from 'resend';
import { NextRequest, NextResponse } from 'next/server';
import MessageUsEmail from '@/components/EmailMessage';
const resend = new Resend(process.env.RESEND_API_KEY);
export async function POST(req: NextRequest) {
const { name, email, message } = await req.json();
try {
const data = await resend.emails.send({
from: 'Hello <rayden@sonya.dev>', // your verified domain
to: `${email}`, // the email address you want to send a message
subject: `${name} has a message!`,
react: MessageUsEmail({ name, email, message }),
});
return NextResponse.json(data);
} catch (error) {
return NextResponse.json({ error });
}
}
From the code snippet above, you did the following:
Imported
Resend
from'resend'
.Imported
NextRequest
andNextResponse
from'next/server'
which are Next.js server-side functions.Imported the
MessageUsEmail
component that is used for generating the content of the email you intend to send.The
RESEND_API_KEY
is used to create an instance of Resend.The
POST
function is an asynchronous function that handles incoming POST requests.The
name
,email
, andmessage
variables are extracted from the parsed request body.
Now, navigate to the homepage of your project and input some data into the form fields. Click the “Book Appointment” button. Messages sent to your email should appear in your inbox.
Conclusion
This tutorial showed how to send emails from a verified domain using React-Email, Next.js, and Resend.
Resources
Official Resend Documentation
Official React Email Documentation
Top comments (3)
How do I send attachments with Resend?
Also is it free to send with attachments?
I was recently looking for a way to implement this in a project and I stumbled upon your post. Thank you for sharing!
I'm glad the tutorial was helpful.
To implement Resend in your existing project,
the main dependencies you'll need to install are:
@react-email/components, react-email, and resend.
Thanks for reading.😊