How to Send Emails from NextJs Using Resend.

sending emails from your website is challenging but with Resend it becomes easier, let's delve how to send emails from our Next.js website.

Resend team present their platform as email for developers,

honestly, they have a right, they provide libraries and documentations for every possible framework from Nodejs, Laravel, Next, Nuxt, even serverless like Supabase and Aws Lambada.

To use Resend inside our Next project, some prerequisites first you need to create Api Key, and verify your domain.

for code first you need to install Resend package using yarn or npm or pnpm:

npm install resend

Create email template:

create emialTemplate.tsx inside components folder,

import * as React from 'react';

interface EmailTemplateProps {
  firstName: string;
  message: string;
}

export const EmailTemplate: React.FC<Readonly<EmailTemplateProps>> = ({
  firstName,message
}) => (
  <div>
    <h1>Welcome, {firstName}!</h1>
    <p>{message}</p>
  </div>
);

For sending email we will create api route file inside app/api/email/route.ts

import { EmailTemplate } from '../../../components/EmailTemplate';
import { Resend } from 'resend';
import { NextRequest} from "next/server";
const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req:NextRequest) {
  try {
       const searchParams = req.nextUrl.searchParams;
    const id = searchParams.get("name");
    const message=  searchParams.get("message");
    const data = await resend.emails.send({
      from: 'youremail@email.com',
      to: ['recipientemail@email.com'],
      subject: 'Greeting Email',
      react: EmailTemplate({ firstName: 'Ismail',message:'hello Ismail' }),
    });

    return Response.json(data);
  } catch (error) {
    return Response.json({ error });
  }
}

Now you can use fetch to call .../api/email?name=recepientName&message=yourMessage

Resend allows you to send up to 3000 emails per month with day limit of 100 emails, this is good as a start.

0
Subscribe to my newsletter

Read articles from ismail abu almagd directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ismail abu almagd
ismail abu almagd

A software developer who found his passion in building successful saas and learn from the journey.