DEV Community

Cover image for How to send a warm welcome email with Resend, Next-Auth and React-Email
Marc Seitz
Marc Seitz

Posted on

How to send a warm welcome email with Resend, Next-Auth and React-Email

What you will find in this article?

We often encounter applications that send us welcome emails whenever we sign up. These emails are usually a way to confirm our email address, guide us about the platform, and make us feel more welcomed. In this article, we will learn how to send a programmatic welcome emails using Resend, Next-Auth.js, and React-Email.

welcome gif

Papermark - the first dynamic open-source alternative to DocSend.

Before we begin, let me introduce you to Papermark. It's an open-source alternative to DocSend that helps you manage secure document sharing, including real-time analytics. It's all open-source!

I would be absolutely thrilled if you could give us a star! Don't forget to share your thoughts in the comments section ❤️
https://github.com/mfts/papermark

Papermark App

Setup the project

Let's go ahead and set up our project environment for our email welcoming application. We'll be creating a Next.js app, and set up the needed services and tools.

Set up tea

Before diving in, it's a good idea to have a package manager handy, like tea. It'll handle your development environment and simplify your life!

sh <(curl https://tea.xyz)

# --- OR ---
# using brew
brew install teaxyz/pkgs/tea-cli
Enter fullscreen mode Exit fullscreen mode

tea frees you to focus on your code, as it takes care of installing node, npm, vercel and any other packages you may need. The best part is, tea installs all packages in a dedicated directory (default: ~/.tea), keeping your system files neat and tidy.

Setting up Next.js with TypeScript and Tailwindcss

We'll use create-next-app to generate a new Next.js project. We'll also be using TypeScript and Tailwind CSS, so make sure to select those options when prompted.

npx create-next-app

# ---
# you'll be asked the following prompts
What is your project named?  my-app
Would you like to add TypeScript with this project?  Y/N
# select `Y` for typescript
Would you like to use ESLint with this project?  Y/N
# select `Y` for ESLint
Would you like to use Tailwind CSS with this project? Y/N
# select `Y` for Tailwind CSS
Would you like to use the `src/ directory` with this project? Y/N
# select `N` for `src/` directory
What import alias would you like configured? `@/*`
# enter `@/*` for import alias
Enter fullscreen mode Exit fullscreen mode

Setup Next-Auth

Next-Auth is the go-to authentication library for Next.js. I'm also installing the prisma-adapter for Next-Auth, which will allow us to use Prisma as our database ORM.

npm install next-auth @next-auth/prisma-adapter
Enter fullscreen mode Exit fullscreen mode

Setup Resend

Resend is a service that lets you send transactional emails via API, perfect for our needs.

npm install resend
Enter fullscreen mode Exit fullscreen mode

Sign Up to Resend and get your API key from https://resend.com. Add this API key to your .env file.

# .env
RESEND_API_KEY="YOUR_API_KEY"
Enter fullscreen mode Exit fullscreen mode

Setup React-Email

React.email is a collection of high-quality, unstyled components for creating beautiful emails using React and TypeScript. It's from the same creators of Resend.

npm install react-email @react-email/components
Enter fullscreen mode Exit fullscreen mode

I'm installing only the components package, but you can also install the full package, which includes the components and a default theme.

Building the application

Now that we have our setup in place, we are ready to start building our application. The main features we'll cover are:

  • User Sign-up
  • Welcome Email Sending
  • Email Template

#1 User Sign-up

This is a modified backend function straight from next-auth's documentation using prisma as the database and Google as the auth provider.

We are sending the welcome email in the function sendWelcomeEmail below.

// pages/api/auth/[...nextauth].ts
import NextAuth, { type NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import prisma from "@/lib/prisma";
import { sendWelcomeEmail } from "@/lib/emails/send-welcome";

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  adapter: PrismaAdapter(prisma),
  session: { strategy: "jwt" },
  callbacks: {
    jwt: async ({ token, user }) => {
      if (!token.email) {
        return {};
      }
      if (user) {
        token.user = user;
      }
      return token;
    },
  },
  events: {
    async createUser(message) {
      const params = {
        user: {
          name: message.user.name,
          email: message.user.email,
        },
      };
      await sendWelcomeEmail(params); // <-- send welcome email
    }
  },
};

export default NextAuth(authOptions);

Enter fullscreen mode Exit fullscreen mode

#2 Welcome Email Sending

This is our second backend function which is called sendWelcomeEmail and it uses resend to send the emails.

// lib/emails/send-welcome.ts
import { Resend } from "resend";
import { WelcomeEmail } from "@/components/emails/welcome";

const resend = new Resend(process.env.RESEND_API_KEY!);

export async function sendWelcomeEmail({name, email}: {name: string | null | undefined, email: string | null | undefined}) {
  const emailTemplate = WelcomeEmail({ name });
  try {
    // Send the email using the Resend API
    await resend.emails.send({
      from: "Marc from Papermark <marc@papermark.io>",
      to: email as string,
      subject: "Welcome to Papermark!",
      react: emailTemplate,
    });
  } catch (error) {
    // Log any errors and re-throw the error
    console.log({ error });
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

#3 Email Template

The actual content of the email is defined here. We customize the look and feel of the email with react-email components.

You can find more email examples here: https://demo.react.email/preview/vercel-invite-user

// components/emails/welcome.tsx
import React from "react";
import {
  Body,
  Button,
  Container,
  Head,
  Heading,
  Html,
  Preview,
  Text,
  Tailwind,
} from "@react-email/components";


interface WelcomeEmailProps {
  name: string | null | undefined;
}

export const WelcomeEmail = ({ name }: WelcomeEmailProps) => {
  const previewText = `Welcome to Papermark, ${name}!`;

  return (
    <Html>
      <Head />
      <Preview>{previewText}</Preview>
      <Tailwind>
        <Body className="bg-white my-auto mx-auto font-sans">
          <Container className="my-10 mx-auto p-5 w-[465px]">
            <Heading className="text-2xl font-normal text-center p-0 my-8 mx-0">
              Welcome to Papermark!
            </Heading>
            <Text className="text-sm">Hello {name},</Text>
            <Text className="text-sm">
              We're excited to have you onboard at <span>Papermark</span>. We
              hope you enjoy your journey with us. If you have any questions or
              need assistance, feel free to reach out.
            </Text>
            <Section className="text-center mt-[32px] mb-[32px]">
              <Button
                pX={20}
                pY={12}
                className="bg-[#00A3FF] rounded text-white text-xs font-semibold no-underline text-center"
                href={`${process.env.NEXT_PUBLIC_BASE_URL}/welcome`}
              >
                Get Started
              </Button>
            </Section>
            <Text className="text-sm">
              Cheers,
              <br />
              The Papermark Team
            </Text>
          </Container>
        </Body>
      </Tailwind>
    </Html>
  );
};
Enter fullscreen mode Exit fullscreen mode

Bonus: preview emails

React-Email has a built-in render function that let's you preview your email templates in the browser. This is super useful for testing and debugging the layout.

  • Add email key to the scripts section of your package.json file.
// package.json
{
  ...
  "scripts": {
    ...
    "email": "email dev --dir ./components/emails --port 3001"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode
  • Run the following command to start the email preview server.
npm run email
Enter fullscreen mode Exit fullscreen mode
  • Open your browser and navigate to http://localhost:3001 to see the preview of your email template.

Image description

Conclusion

And there you have it! We've built a system for sending welcome emails using Resend, Next-Auth and React-Email. While the example here is simple, the same concepts can be expanded to handle any kind of email your app might need to send.

Thank you for reading. I am Marc, an open-source advocate. I am building papermark.io - the open-source alternative to DocSend.

To me, coding is a continuous journey of learning and discovery. So keep coding, my friends!

Help me out!

If you found this article helpful and got to understand Resend, Next-Auth and React-Email a bit better, I would be extremely glad if you could give us a star! And don't forget to share your thoughts in the comments ❤️

https://github.com/mfts/papermark

cat thanks

Top comments (7)

Collapse
 
nyxb profile image
nyxb

in your // components/emails/welcome.tsx snippet the Section for imports is missing.

Otherwise great article

Collapse
 
bukinoshita profile image
Bu Kinoshita

Hey, Bu here from Resend.
Great article 🖤

Collapse
 
mfts profile image
Marc Seitz

Thanks Bu 😍 Appreciate the feedback

Collapse
 
shunkakinoki profile image
Shun Kakinoki

This is an interesting article - thank you for putting it out!

Collapse
 
mfts profile image
Marc Seitz

Thanks Shun! Glad you enjoyed it. I hope it brings you value :)

Collapse
 
shnai0 profile image
Iuliia Shnai

It would be interesting to see also how to craft best welcome emails or what are the great examples

Collapse
 
mfts profile image
Marc Seitz

React-Email makes it super easy to create beautiful emails, what's missing is a repository of all amazing emails from the top saas companies. These are best practices. React-Email collected a few templates here: demo.react.email/preview/vercel-in...