Before we begin, if you are a video learner - here is a youtube video tutorial for this as well - https://youtu.be/ZF3vHcs9U3s
For this tutorial we are gonna use React Email, Resend & NextJS (App Router)
Initialise a NextJS Project and install the following dependencies
npm install react-email -D -E
npm install @react-email/components react react-dom -E
Create a “emails“ folder in your ./app
dir and then add this script into your package.json
file
{
"scripts": {
"email": "email dev --dir app/emails"
}
}
Design your Email Template
Go to your /app/emails
dir and create a new file and name it EmailTemplate.tsx
import { Button, Html } from "@react-email/components";
import * as React from "react";
export default function EmailTemplate() {
return (
<Html>
<Button
href="https://example.com"
style={{ background: "#000", color: "#fff", padding: "12px 20px" }}
>
Click me
</Button>
</Html>
);
}
Preview your Email Template
Now run -
npm run email
This should start a new localhost server that you can open up in your browser and preview the email that you will be designing in EmailTemplate.tsx
API Endpoint
Finally now we can create our api endpoints. The location of this endpoint would be ./app/api/emails/route.ts
import EmailTemplate from "@/app/emails/EmailTemplate";
import { Resend } from "resend";
const resend = new Resend("API_KEY");
export async function POST(req: Request) {
const { email } = await req.json();
try {
const { data, error } = await resend.emails.send({
from: "Acme <onboarding@resend.dev>",
to: [email],
subject: "This is a test email",
react: EmailTemplate({ buttonText: "Visit my boilerplate" }),
});
return Response.json({ data }, { status: 200 });
} catch (error) {
return Response.json({ error }, { status: 500 });
}
}
Now your endpoint is ready you can simply send requests using a fetch function passing email address of the receiver in the body.
Postman Example:
Thank you!
Follow me on X - https://x.com/khushaal_04
Youtube Guide - https://youtu.be/ZF3vHcs9U3s