On this article, we’ll take a look at the way to ship emails with React E-mail and Resend. We’ll additionally construct a typical portfolio contact kind for sending these emails utilizing Subsequent.js.
Till just lately, creating and sending emails in React was extraordinarily tough, as there was no correct documentation on the way to create e-mail templates with hacky <desk>
tag tips, or documentation on the way to ship emails.
A lot of the problem with utilizing emails has been alleviated by the creation of React E-mail and Resend. These merchandise — which had been developed by the identical group — have created an incredible developer expertise for working with emails.
Setting Up the Subsequent App
Let’s begin by establishing Subsequent.js. Clone the starter department of this GitHub repo to get the starter code. The picture beneath reveals what we should always see once we run the event server.
The starter code consists of a easy Subsequent.js 13 app (with the App Router) that has a contact kind element with correct validation utilizing Zod and React Hook Kind.
We’ll be implementing the onSubmit
operate within the contact kind element:
operate onSubmit(values: z.infer<typeof formSchema>) {
console.log(values);
}
Observe: we received’t cowl the way to construct the shape or the way to model the e-mail itself, as that may be executed with Tailwind or common CSS.
Setting Up Resend
Le’t now take a look at the way to arrange Resend.
Getting the API key
To ship the e-mail with the Resend SDK, we first must retrieve an API key. Head over to Resend’s web site and log in or create an account along with your e-mail or GitHub particulars.
After you’ve logged in, it’s best to see the dashboard as pictured beneath.
Press the Add API Key button to get the API key. After you have your API key, go to the basis of the venture and create a .env.native
file and paste the API key as follows:
RESEND_API_KEY=************
This can permit us, afterward, to make use of Resend providers inside our app.
Verifying a site
Resend requires that we confirm a site from which we wish to ship limitless emails by including a DNS file on their web site.
To do that, head over to the Resend dashboard and go to the Domains tab and press the Add Area button, as pictured beneath.
From there, we are able to confirm the area and use that particular e-mail handle. For this straightforward tutorial, we received’t be verifying any e-mail addresses.
Creating the E-mail Element
It’s now time to create the e-mail element. Within the parts
folder, create a file known as E-mail.tsx
and import the next parts from React E-mail:
import {
Physique,
Container,
Head,
Heading,
Hr,
Html,
Preview,
Tailwind,
Textual content,
} from "@react-email/parts";
import * as React from "react";
For the e-mail, the one issues that may change would be the kind information values (that’s, the title, message, e-mail handle, and cellphone variety of the individual). These values can be utilized as props for the e-mail, so let’s create an interface for that:
interface ContactMeEmailProps {
title: string;
emailAddress: string;
phoneNumber: string;
content material: string;
}
The precise e-mail element would seem like this:
const VercelInviteUserEmail = ({
title,
content material,
emailAddress,
phoneNumber,
}: ContactMeEmailProps) => {};
For the preview textual content of the e-mail, we may simply say that “so and so has a message”. It could be applied like this:
const previewText = `${title} has a message`;
Now for the precise JSX. We’ll first must wrap our e-mail in an <Html>
tag and render the <Head>
and <Preview>
tags (for the preview textual content). Then we have to wrap the content material in a <Tailwind>
tag to make use of Tailwind styling, and a <Physique>
tag:
<Html>
<Head />
<Preview>{previewText}</Preview>
<Tailwind>
<Physique className="bg-white my-auto mx-auto font-sans">
{...}
</Physique>
</Tailwind>
</Html>
We are able to then add a <Container>
element with some basic styling to make the container through which the e-mail is rendered look nicer:
<Container className="border border-solid border-[#eaeaea] rounded
my-[40px] mx-auto p-[20px] w-[465px]">
</Container>
Then contained in the container, we are able to add a easy heading with some types labeled “Somebody want to contact you about one thing!”
<Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">
<sturdy>{title}</sturdy> want to contact you about one thing!
</Heading>
Then we are able to render out the precise content material of the e-mail with the built-in <Textual content>
element:
<Textual content className="text-black text-[14px] leading-[24px]">
Right here is the message:
</Textual content>
<Textual content className="text-black text-[14px] leading-[24px]">
{content material}
</Textual content>
Lastly, we are able to add an <Hr>
element and one other <Textual content>
element with the sender’s contact data for future conversations:
<Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" />
<Textual content className="text-[#666666] text-[12px] leading-[24px]">
This message was despatched by ${title}. You may contact him by his
e-mail {emailAddress} or his cellphone quantity {phoneNumber}
</Textual content>
And with that, our e-mail is completed. As you’ve in all probability observed, React E-mail makes it easy to make emails, as a result of its built-in parts are virtually equivalent to common HTML tags.
The e-mail ought to look one thing just like the picture beneath.
Now we’re able to ship the e-mail with Resend!
Sending the E-mail with Resend
To ship the e-mail, we first must implement the API endpoint. Within the file api/ship/route.ts
(already created in starter information), ensure that the next imports are current:
import ContactMeEmail from "@/parts/E-mail";
import { NextRequest, NextResponse } from "subsequent/server";
import { Resend } from "resend";
import * as z from "zod";
Then, create an occasion of the Resend SDK, as follows:
const resend = new Resend(course of.env.RESEND_API_KEY);
Observe: should you used a distinct setting variable title on your API key, ensure that to interchange it correctly.
Then paste within the following Zod schema:
const sendRouteSchema = z.object({
title: z.string().min(2),
emailAddress: z.string().e-mail(),
phoneNumber: z.string().min(2),
content material: z.string().min(2),
});
This schema represents the request physique that was despatched from the consumer. Now let’s destructure the request physique to get these fields within the POST
operate:
const { title, emailAddress, phoneNumber, content material } = await req
.json()
.then((physique) => sendRouteSchema.parse(physique));
Now, to ship the e-mail, we use the ship
operate from our Resend occasion like this:
const information = await resend.emails.ship({
from: "from e-mail",
to: ["delivery email"],
topic: `${title} has a message!`,
react: ContactMeEmail({ title, emailAddress, phoneNumber, content material }),
});
For those who verified your area on Vercel, you need to use an e-mail handle with that area on the from
subject, and the to
subject needs to be your e-mail. If you wish to be further safe with the e-mail addresses, you possibly can set them as setting variables.
Now we have to implement the precise fetch motion on the consumer. Within the contact kind element (parts/ContactForm.tsx
), we have to fetch the API endpoint like this within the onSubmit
operate:
await fetch("/api/ship", {
technique: "POST",
physique: JSON.stringify({
title: values.title,
emailAddress: values.e-mail,
phoneNumber: values.cellphone,
content material: values.content material,
}),
});
Make sure that to mark the operate as async
because of the await assertion. It’s as much as you to resolve the way you wish to implement loading and error-handling states. (You may learn extra about async/await right here.)
And with that, we have now efficiently despatched the e-mail with Resend!
Conclusion
A lot of the headache with creating and sending emails in React has been solved with React E-mail and Resend. It’s a two-hit combo that gives an incredible developer expertise and will get the job executed extraordinarily shortly.
Seek the advice of the docs for React E-mail and Resend if you wish to study extra about these frameworks. React E-mail additionally supplies many instance templates so that you can base your emails off.
You could find the completed supply code on GitHub.