Send Stunning Emails with Next.js and Tailwind CSS

Send Stunning Emails with Next.js and Tailwind CSS

Elevate Your Brand with Fully Customized Designs! ๐Ÿคฏ๐Ÿ˜

ยท

5 min read

Have you ever seen beautiful emails like the one below, and have wanted to send one too?

Creative Email Samples

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)

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 ๐Ÿ‘ˆ๐Ÿป :

Create NextJS project

npx create-next-app@latest mail-synk

Install TailwindCSS and configure it

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.

/** @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.

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

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

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,

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 :
"email" : "email dev"
  • Create a new folder called emails and add our own templates inside it

  • Run the following command :

npm run email

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

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 ๐Ÿ‘‡๐Ÿป :

Or you can edit this UI by @zenorocha :

React Email

Copy my Email Template ๐Ÿ‘ˆ๐Ÿป 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โ›บ๏ธ to get a free domain.

  • One you are done, you can go to Vercel โœŒ๐Ÿป .

  • Head on to Domains dashboard ๐Ÿ‘‡๐Ÿป and add your domain :

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

Resend Domains

  • You will see some configurations, that you need to add to your Nameservers settings. Follow the guide as shown in the official guides here ๐Ÿ‘‰๐Ÿป

  • 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 ๐Ÿ› ๏ธ :

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 :

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 :

npm run dev

And open the following link on your browser :

http://localhost:3000/api/mailer

You will see a response like this :

{
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๐Ÿš€

ย