How to Send Email Using Resend and Next.js

How to Send Email Using Resend and Next.js

authorBy Kaimul
5 min read

Learn how to Send Email Using Resend and Next.js + server actions.


Suppose you're working on a Next.js 14 project with a contact form and you need to set up email communication for your users. You're in the right place. This guide will help you set up your email efficiently using Resend and Next.js.

Welcome to this comprehensive guide on integrating email functionality into your Next.js application using the Resend Node.js SDK. This tutorial will walk you through each step, from setting up your Resend account to deploying a contact form that sends emails. Let's dive in!

Step 1: Install Resend

Begin by adding the Resend Node.js SDK to your project. Open your terminal and execute the following command:

>_Terminal
npm install resend

Step 2: Sign in or Sign Up for Resend

Navigate to Resend's login page to access your account. If you're new to Resend, you'll need to sign up and create an account. Once logged in, proceed to your dashboard to retrieve or generate your API key.

Securely store your API key in your project's .env file as follows:

.env
RESEND_API_KEY=your_unique_api_key

3. Set up a server action file.

Instead of an API route file, we will create an action file, app/action/sendEmail.ts. This file will handle email sending functionality and operate as an API route. Below, I explain how this file works.

sendEmail() accepts firstName, lastName, email address, and message as formData (Explore the FormData() docs) props from the ContactForm.tsx component. A FormData object consists of [key, value] pairs. If we execute console.log(formData), we will see the following.

console
formdata _FormData [FormData] { [Symbol(state)]: [ { name: 'firstName', value: 'kaimul' }, { name: 'lastName', value: 'alam' }, { name: 'senderEmail', value: 'alam@yahoo.com' }, { name: 'message', value: 'formdata testing' } ] }

This process involves user input in the form of formData, which is then sent as an email to the admin. Only the value will appear in the email, so we need to extract this value from the formData using the get() method. For instance,

js
const firstName = formData.get("firstName"); // kaimul console.log(firstName); const lastName = formData.get("lastName"); //alam const email = formData.get("senderEmail"); //alam@gmail.com const message = formData.get("message"); // formdata testing

We are passing these variables: firstName, lastName, email, and message, to the EmailTemplate.tsx component as props.

The complete code for app/action/sendEmail.ts will look like the following:

app/action/sendEmail.ts
"use server"; import EmailTemplate from "@/components/Email/Email-template"; import { Resend } from "resend"; const resend = new Resend(process.env.RESEND_API_KEY); export const sendEmail = async (formData: FormData) => { console.log("formdata", formData); const firstName = formData.get("firstName"); //console.log(firstName); const lastName = formData.get("lastName"); const email = formData.get("senderEmail"); const message = formData.get("message"); //console.log(message); try { const data = await resend.emails.send({ from: "onboarding@resend.dev", to: "kaimuljewel@yahoo.com", subject: `message from ${firstName}`, reply_to: email as string, //firstName: firstName as string, text: message as string, react: EmailTemplate({ firstName: firstName as string, lastName: lastName as string, message: message as string, email: email as string, }), }); return JSON.parse(JSON.stringify(data)); } catch (error) { console.error(error); throw new Error("failed to send email"); } };

Step 4: Create an Email Template.

Create an email template at components/email-template.tsx. that structures the email content. Here’s an example component:

components/email-template.tsx
import React from "react"; type EmailTemplateProps = { firstName: string; lastName: string; email: string; message: string; }; export default function EmailTemplate({ firstName, lastName, email, message, }: EmailTemplateProps) { return ( <div> <h2> Hi Admin, <br /> You received this email from{" "} <span style={{ color: "blue" }}> {firstName} {""} {lastName} </span>{" "} who enquired about the following. </h2> <p>{message}</p> <br /> <h4>Kind Regards</h4> <p> {firstName} {lastName} </p> <span>Email: {email} </span> </div> ); }

Step 5: Create a Contact Form.

Next, create a simple contact form in the component folder component/ContactForm.tsx. This form will collect user input for the first name, last name, email address, and message. Here is an example component:

component/ContactForm.tsx
import React, { useRef, useState } from "react"; import styles from "./contactForm.module.scss"; import { sendEmail } from "@/app/action/sendEmail"; import { SubmitButton } from "../SubmitButton/SubmitButton"; export default function ContactForm() { const [isSubmit, setIsSubmit] = useState(false); const ref = useRef<HTMLFormElement>(null); return ( <form action={async (formData)=> { await sendEmail(formData); setIsSubmit(true); ref.current?.reset(); setTimeout(()=> { setIsSubmit(false); }, 3000); }} ref={ref} className={styles.form} > <input name="firstName" type="text" placeholder="First Name" /> <input name="lastName" type="text" placeholder="Last Name" /> <input name="senderEmail" type="email" id="email" placeholder="Please Enter Your Email Address" required /> <textarea name="message" required cols={30} rows={10} placeholder="Write your message here" ></textarea> {/* <button type="submit" className={styles.submit}> Submit </button> */} <SubmitButton /> {isSubmit && ( <p className={styles.notification}> Your message has been sent successfully. </p> )} </form> ); }

Once everything is set up correctly, you can open your email inbox to check for new messages. For instance, your inbox might display something like this:

email inbox

Conclusion

By integrating Resend with Next.js, you can manage emails in your applications easily. Following these steps will set up a strong email system that improves user interaction and supports your business needs. Your Next.js application is now ready to handle different email tasks such as customer support, notifications, or marketing effectively.