Send Emails with Next.js and Tailwind CSS
Tags: nextjs, react, tailwindcss, codenewbie
Published: 2023-09-23 15:20:22


## Elevate Your Brand with Fully Customized Designs! 🤯😍
Have you ever seen beautiful emails like the one below, and have wanted to send one too?

![Creative Email Samples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/of1dfvxlmfj45sdl2hfi.png)

Well, I am here to tell you that it's really easy.

## Pre-Requisites ⚙️
To being able to create such stunning emails, you will need to know the following : 
- TailwindCSS 
- NodeJS + ReactJS **OR** NextJS
- React-Email Library(Optional)
- Resend or Nodemailer (I will discuss both)

<img src="https://media.giphy.com/media/w9xG5hsxZlqtevPlJQ/giphy.gif" alt="woaaaah"/>

## Getting Started
Okay, so the first step is to create a `NextJS + TailwindCSS` project. For this we use the following steps (also present [here 👈🏻](https://tailwindcss.com/docs/guides/nextjs) : 
### Create NextJS project
```js
npx create-next-app@latest mail-synk
```
### Install TailwindCSS and configure it
```js
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
```
### Configure your template paths

Add the paths to all of your template files in your `tailwind.config.js file.`

```js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
 
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
```

### Add the Tailwind directives to your CSS

Add the `@tailwind` directives for each of Tailwind’s layers to your `globals.css` file.
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```

### Install `Resend` and `React-Email`
Now install Resend and React-Email as there are what will help us in creating the amazing Email templates that you see.

```js
npm install resend react-email @react-email/components
```

## Resend and React-Email
Resend and React-Email, both created by @zenorocha as great tools for the creation and sending of beautiful emails using ReactJS/ NextJS. 


![Resend Docs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcrcoc73zaeu36y7qmpx.png)

As it says on their homepage : 
### The best API to reach humans instead of spam folders. Build, test, and deliver transactional emails at scale.

And with `React-Email` that provides us 👇🏻: 
### A collection of high-quality, unstyled components for creating beautiful emails using React and TypeScript.

They basically form an :
- Easy to configure
- Component Based
- Email Sending Service
- With Ability to bundle with Tailwind for CSS Styling
architecture, with support for various mailing clients.

## Enough With Talk, Time for Code 🧑🏼‍💻
Now that the setup and introduction of the libraries are done,
<img src="https://media.giphy.com/media/Ws6T5PN7wHv3cY8xy8/giphy.gif" alt="time to code meme"/>

React-email recommends and works the best when you use the `components` provided by the library ( we installed them earlier)

But to be able to view the React-Email component changes, we have to : 
- Add the following script to the `package.json` file : 
```json
"email" : "email dev"
```
- Create a new folder called `emails` and add our own templates inside it
- Run the following command :
```js
npm run email
```

> ### But the above server is really slow to build, I mean really slow.

<img src="https://media.giphy.com/media/bMdZu3fG2ZEBO/giphy.gif" alt='so slow'/>

So instead of using the `email` server, we use the normal `dev` server of `NextJS` to create the template and view it and then convert it into a `React-Email components` based format(which is super easy).

## Building the Email 🛠️
The most important part of this application is the actual mail. 
There are some limitations while using `TailwindCSS` to create this email : 
- You will note🚨 be able to use Grid or FlexBox.
- Responsive design is possible but `doesn't render properly ⚠️`.
- Shadows and Background Gradients do not work.

So sticking to a simple UI, you can create one like I built 👇🏻 : 
[
![Email Template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bg8se24hrtf0xe76q45j.png)](https://www.thevinitgupta.tech/email)

Or you can edit this UI by @zenorocha :

![React Email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/790fymo0h1ui94vqv59h.png)

Copy my [Email Template](https://github.com/thevinitgupta/Mail-Sync/blob/main/emails/job.jsx) 👈🏻 Here.

## Points to Convert The NextJS code to Email Template
The original NextJS code is as below, and you have to make changes as following to create an email template that can be rendered properly : 
- Wrap the whole component in `<HTML></HTML>` tags.
- Add `<Tailwind></Tailwind>` tags if you are using Tailwind CSS otherwise don't.
- Create a `<Body></Body>` component inside the Tailwind component and write all you Template Code inside this.
- Replace `<div>` with `Section` or `Container` components and `<p>` tags with `Text`.
- Use `Link` components for Links.
- And `Img` for images.

> ### 📌 Remember, to import all of the above from `@react-email/components`.

## Registering on Resend 
Now Resend requires us to create an account and use a verified domain to send the Emails. 
If you have a domain you can use it for the same, or if you are a student, you can use the following guide by [FreeCodeCamp⛺️](https://www.freecodecamp.org/news/github-student-developer-pack/) to get a free domain.

- One you are done, you can go to [Vercel ✌🏻 ](https://www.vercel.com).

- Head on to Domains dashboard 👇🏻 and add your domain : 
![Vercel Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orrn3hwe0idfn9z2adxr.png)

- Add the Domain to Resend dashboard, using the Add Domain button as shown : 

![Resend Domains](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3amq1vrnzz9imwl3z243.png)

- You will see some configurations, that you need to add to your Nameservers settings.
Follow the guide as shown in the official guides [here 👉🏻](https://resend.com/docs/dashboard/domains/introduction)

- Create a New API key from Resend, once your Domain has been verified.


## Setting Up the API Routes
Inside the `src` route you will see an `api` folder.
Create a new file inside the folder called : `mailer.js`(or any other name that you like) and add the following code to use resend 🛠️ : 
```js
mport { Email } from '../../../Emails/mail.js';
import { NextResponse } from 'next/server';
import { Resend } from 'resend';

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

export async function GET() {
  try {
    const data = await resend.emails.send({
      from: 'Your Name <youremail@domain.dev>',
      to: ['receiver@domain.dev'],
      subject: 'Add a Subject',
      react: Email({ firstName: 'Vinit' }),
    });

    return NextResponse.json(data);
  } catch (error) {
    return NextResponse.json({ error });
  }
}
```

### For using Nodemailer 📧, use the below code : 
```js
const apiKey = process.env.RESEND_API_KEY;
    try {
        const transporter = nodemailer.createTransport({
          host: 'smtp.resend.com',
          secure: true,
          port: 465,
          auth: {
            user: 'resend',
            pass: apiKey,
          },
        });
      const htmlString = render(Email({
        name
      }), {
        pretty: true,
      });

      const info = await transporter.sendMail({
        from: '"Vinit Gupta" <vinit@thevinitgupta.tech>', // sender address
        to: email, // list of receivers
        subject: `Software Engineer Opportunities in ${location}`, // Subject line
        html : htmlString // html body
      });
       res.status(200).send(htmlString)
      } catch (error) {
        console.log(error)
         res.status(200).json({ message : error.message });
      }
```

## Sending the Email
Now run the following command on your shell to start your NextJS server : 
```js
npm run dev
```

And open the following link on your browser : 
```js
http://localhost:3000/api/mailer
```

You will see a response like this : 
```js
{
messageId : "fsg5yerhtrys"
}
```

And there you have it : Your Personal Email Marketing or Referral Asking Application!! 

## Share this app with your friends and post their reactions on Twitter and tag me : [thevinitguptaa🚀](https://twitter.com/thevinitguptaa)