How to send a warm welcome email with Resend, Next-Auth and React-Email
Tags: resend, nextjs, email, tutorial
Published: 2023-06-19 13:53:35

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pj053r1hugrbo0ugg6bx.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](https://github.com/mfts/papermark)


[![Papermark App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igzk8cdssbmla9uf1544.png)](https://github.com/mfts/papermark)




## 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`](https://github.com/teaxyz/cli). It'll handle your development environment and simplify your life!

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

# --- OR ---
# using brew
brew install teaxyz/pkgs/tea-cli
```

`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.

```bash
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
```

### 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.


```bash
npm install next-auth @next-auth/prisma-adapter
```

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

```bash
npm install resend
```

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

```bash
# .env
RESEND_API_KEY="YOUR_API_KEY"
```

### Setup React-Email

[React.email](https://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.

```bash
npm install react-email @react-email/components
```

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.  

```ts
// 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);

```

### #2 Welcome Email Sending
This is our second backend function which is called `sendWelcomeEmail` and it uses `resend` to send the emails.

```ts
// 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;
  }
}
```


### #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

```tsx
// 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>
  );
};
```


### 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.
```json
// package.json
{
  ...
  "scripts": {
    ...
    "email": "email dev --dir ./components/emails --port 3001"
  },
  ...
}
```

- Run the following command to start the email preview server.
```bash
npm run email
```

- Open your browser and navigate to `http://localhost:3001` to see the preview of your email template.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jvbix9wo6egylz5proa.png)



## 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](https://www.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](https://github.com/mfts/papermark)

![cat thanks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3etxn9ugxefj3jhwidgi.gif)