DEV Community

Cover image for Send Emails with Next.js and Tailwind CSS
Vinit Gupta
Vinit Gupta

Posted on • Updated on

Send Emails with Next.js and Tailwind CSS

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

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
Enter fullscreen mode Exit fullscreen mode

Install TailwindCSS and configure it

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

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: [],
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
  • Create a new folder called emails and add our own templates inside it
  • Run the following command :
npm run email
Enter fullscreen mode Exit fullscreen mode

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 πŸ‘‡πŸ» :

Email Template

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 :
    Vercel Dashboard

  • 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 });
  }
}
Enter fullscreen mode Exit fullscreen mode

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 });
      }
Enter fullscreen mode Exit fullscreen mode

Sending the Email

Now run the following command on your shell to start your NextJS server :

npm run dev
Enter fullscreen mode Exit fullscreen mode

And open the following link on your browser :

http://localhost:3000/api/mailer
Enter fullscreen mode Exit fullscreen mode

You will see a response like this :

{
messageId : "fsg5yerhtrys"
}
Enter fullscreen mode Exit fullscreen mode

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πŸš€

Top comments (11)

Collapse
 
nevodavid profile image
Nevo David

Great stuff!

Collapse
 
thevinitgupta profile image
Vinit Gupta

Thanks a lot Nevo!!

Collapse
 
pizofreude profile image
Pizofreude

I like practical tutorial like this, kudos Vinit!

Collapse
 
thevinitgupta profile image
Vinit Gupta

ThanksπŸ™
I'll try to drop in some more

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Really nicely written article Vinit!

Collapse
 
thevinitgupta profile image
Vinit Gupta

Thanks Nathan πŸš€

Collapse
 
starkraving profile image
Mike Ritchie • Edited

Does the service take the atomic classes and expand them into the actual inline style rules? Because some email clients can’t handle embedded stylesheets or class names

Collapse
 
thevinitgupta profile image
Vinit Gupta

Yes Mike, this is what is being done. Since many email clients can't handle embedded stylesheets or class names.

This ensures that the final HTML sent to email clients only contains inline style attributes, which are well supported.

Collapse
 
abdiselam13 profile image
Abdiselam muktar

I need a monter bro guide me if you can

Collapse
 
thevinitgupta profile image
Vinit Gupta

Sure drop me a message on LinkedIn and I would love to

Collapse
 
richhomiechief profile image
richhomieChief

This is great. What's the limit to mails I can send at once?