On this article, we’ll have a look at how one can ship emails with React Electronic 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 troublesome, as there was no correct documentation on how one can create e-mail templates with hacky <desk>
tag tips, or documentation on how one can ship emails.
A lot of the problem with utilizing emails has been alleviated by the creation of React Email and Resend. These merchandise — which have been developed by the identical workforce — have created a tremendous developer expertise for working with emails.
Setting Up the Subsequent App
Let’s begin by organising Subsequent.js. Clone the starter department of this GitHub repo to get the starter code. The picture under reveals what we should always see after 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 Form.
We’ll be implementing the onSubmit
perform within the contact kind element:
perform onSubmit(values: z.infer<typeof formSchema>) {
console.log(values);
}
Word: we received’t cowl how one can construct the shape or how one can model the e-mail itself, as that may be carried out with Tailwind or common CSS.
Setting Up Resend
Le’t now have a look at how one can 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 website and log in or create an account together with your e-mail or GitHub particulars.
After you’ve logged in, you must see the dashboard as pictured under.
Press the Add API Key button to get the API key. After you have your API key, go to the foundation of the undertaking and create a .env.native
file and paste the API key as follows:
RESEND_API_KEY=************
This can permit us, in a while, to make use of Resend companies 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 report 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 under.
From there, we are able to confirm the area and use that particular e-mail tackle. For this straightforward tutorial, we received’t be verifying any e-mail addresses.
Creating the Electronic mail Part
It’s now time to create the e-mail element. Within the elements
folder, create a file known as Electronic mail.tsx
and import the next elements from React Electronic mail:
import {
Physique,
Container,
Head,
Heading,
Hr,
Html,
Preview,
Tailwind,
Textual content,
} from "@react-email/elements";
import * as React from "react";
For the e-mail, the one issues that may change would be the kind information values (that’s, the identify, message, e-mail tackle, 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 {
identify: string;
emailAddress: string;
phoneNumber: string;
content material: string;
}
The precise e-mail element would seem like this:
const VercelInviteUserEmail = ({
identify,
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 might be applied like this:
const previewText = `${identify} 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 will then add a <Container>
element with some common styling to make the container by 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 kinds labeled “Somebody wish to contact you about one thing!”
<Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">
<sturdy>{identify}</sturdy> wish 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 ${identify}. You possibly can contact him by his
e-mail {emailAddress} or his cellphone quantity {phoneNumber}
</Textual content>
And with that, our e-mail is finished. As you’ve in all probability observed, React Electronic mail makes it easy to make emails, as a result of its built-in elements are virtually equivalent to common HTML tags.
The e-mail ought to look one thing just like the picture under.
Now we’re able to ship the e-mail with Resend!
Sending the Electronic 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), be sure the next imports are current:
import ContactMeEmail from "@/elements/Electronic 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);
Word: if you happen to used a distinct setting variable identify to your API key, be sure to switch it correctly.
Then paste within the following Zod schema:
const sendRouteSchema = z.object({
identify: 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 shopper. Now let’s destructure the request physique to get these fields within the POST
perform:
const { identify, emailAddress, phoneNumber, content material } = await req
.json()
.then((physique) => sendRouteSchema.parse(physique));
Now, to ship the e-mail, we use the ship
perform from our Resend occasion like this:
const information = await resend.emails.ship({
from: "from e-mail",
to: ["delivery email"],
topic: `${identify} has a message!`,
react: ContactMeEmail({ identify, emailAddress, phoneNumber, content material }),
});
In case you verified your area on Vercel, you need to use an e-mail tackle with that area on the from
discipline, and the to
discipline must be your e-mail. If you wish to be additional safe with the e-mail addresses, you’ll be able to set them as setting variables.
Now we have to implement the precise fetch motion on the shopper. Within the contact kind element (elements/ContactForm.tsx
), we have to fetch the API endpoint like this within the onSubmit
perform:
await fetch("/api/ship", {
methodology: "POST",
physique: JSON.stringify({
identify: values.identify,
emailAddress: values.e-mail,
phoneNumber: values.cellphone,
content material: values.content material,
}),
});
Be certain to mark the perform as async
as a result of await assertion. It’s as much as you to resolve the way you wish to implement loading and error-handling states. (You possibly can read more about async/await here.)
And with that, we’ve 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 Electronic mail and Resend. It’s a two-hit combo that gives a tremendous developer expertise and will get the job carried out extraordinarily rapidly.
Seek the advice of the docs for React Email and Resend if you wish to be taught extra about these frameworks. React Electronic mail additionally gives many example templates so that you can base your emails off.
You’ll find the completed supply code on GitHub.