Step-by-Step Guide to Crafting Professional Emails with Mailgen and Nodemailer

Indranil MaitiIndranil Maiti
5 min read

You receive countless polished and branded emails in your inbox every day. Have you ever wondered how to integrate such professional emails into your web application? Today, we will explore how to create and send professional, polished-looking emails to your users using Mailgen and Nodemailer.

I will show you one example here. I will give an example here on how you can craft a welcome email when users register first in your web application with a link to verify their account i.e. a verification email to your user.

We will write the utility files first. The goal is to create small, reusable functions that can be used based on their specific use cases in your web application.

Installation

Install mailgen and nodemailer first.

npm i mailgen nodemailer

Also, create an account on Mailtrap and set up your account. We will use their service to test our trial emails. Once done, let us start step by step.

Step 1: Create Mailgen Instance (Configure your email based on your product)

Here I have created mailGenerator instance using Mailgen Class to configure mailgen depending on your product details and theme. You can configure it using your company logo as well.


    var mailGenerator = new Mailgen({
        theme: 'default',
        product: {
            // Appears in header & footer of e-mails
            name: 'Task Manager', // Your Product
            link: 'Your website link'
            // Optional product logo
            // logo: 'https://mailgen.js/img/logo.png'
        }
    });

You might need to send multiple emails to your users. For example, you could send a link to reset a password, a link to restore a password, or some promotional emails. You will like to have separate email functions to generate separate emails. This will be easy to manage for large projects.

emailVerificationmailgenContent function will be used to generate an email containing a link to verify their email when they first register on your application. username and verificationUrl you can set it up in your registerUser controller.

const emailVerificationmailgenContent = (username, verificationUrl) => {
    return {
        body : {
            name: username,
            intro: 'Welcome to Mailgen! We\'re very excited to have you on board.',
            action: {
                instructions: 'To get started with Our App, please click here:',
                button: {
                    color: '#22BC66', // button colour
                    text: 'Verify your email', // text on the button
                    link: verificationUrl // Link to verify user
                } 
        },
         outro: 'Need help, or have questions? Just reply to this email, we\'d love to help.'
    }
}
}

You can similarly build a separate function to send a reset password link.

const forgotPasswordmailgenContent = (username, passwordresetUrl) => {
    return {
        body : {
            name: username,
            intro: 'Reset your password',
            action: {
                instructions: 'To change your password click the button',
                button: {
                    color: '#22BC66', 
                    text: 'reset password',
                    link: passwordresetUrl
                } 
        },
         outro: 'Need help, or have questions? Just reply to this email, we\'d love to help.'
    }
}
}

In this step, we will use mailGenerator to craft the email now. mailgenContent is the main content that is going to be sent along with the email. We will use emailVerificationmailgenContent() to generate mailgenContent that is used here.

 // Generate the plaintext version of the e-mail (for clients that do not support HTML)
var emailText = mailGenerator.generatePlaintext(mailgenContent); 
// Generate an HTML email with the provided contents
var emailBody = mailGenerator.generate(mailgenContent);

Step 3: Send the email using Nodemailer

We have crafted our email. Now it’s the time to send emails. This is a standard nodemailer function to send the crafted email.

const transporter = nodemailer.createTransport({
    host: process.env.MAILTRAP_HOST,
    port: process.env.MAILTRAP_PORT,
    secure: false, // true for port 465, false for other ports
    auth: {
        user: process.env.MAILTRAP_USERNAME,
        pass: process.env.MAILTRAP_PASSWORD,
    },
});

const mailOptions = {
    from: 'youremail@gmail.com', // sender address
    to: email, // list of receivers
    subject: subject, // Subject line
    text: emailText,
    html: emailBody
}

try {
    await transporter.sendMail(mailOptions)
} catch (error) {
    console.error("Email failed", error)
}

Let us use what we have learnt so far

Let us bring all the things together and use them.

To sum up, what does the complete utility file look like now? The main thing here is to look at mailgen() function. The function takes options as an argument, which is an object containing mailgenContent, email, and subject.

Rest of the code is pretty familiar to you now and you also know the purpose of each segment now.

import Mailgen from 'mailgen'
import nodemailer from 'nodemailer'

const mailgen = async (options) => {
    var mailGenerator = new Mailgen({
        theme: 'default',
        product: {
            name: 'Task Manager',
            link: 'https://mailgen.js/'
        }
    });

// Generate the plaintext version of the e-mail (for clients that do not support HTML)
var emailText = mailGenerator.generatePlaintext(options.mailgenContent);
var emailBody = mailGenerator.generate(options.mailgenContent);

const transporter = nodemailer.createTransport({
    host: process.env.MAILTRAP_HOST,
    port: process.env.MAILTRAP_PORT,
    secure: false, // true for port 465, false for other ports
    auth: {
        user: process.env.MAILTRAP_USERNAME,
        pass: process.env.MAILTRAP_PASSWORD,
    },
});

const mailOptions = {
    from: 'indranilmaiti1@gmail.com', // sender address
    to: options.email, // list of receivers
    subject: options.subject, // Subject line
    text: emailText,
    html: emailBody
}

try {
    await transporter.sendMail(mailOptions)
} catch (error) {
    console.error("Email failed", error)
}
}

const emailVerificationmailgenContent = (username, verificationUrl) => {
    return {
        body : {
            name: username,
            intro: 'Welcome to Mailgen! We\'re very excited to have you on board.',
            action: {
                instructions: 'To get started with Our App, please click here:',
                button: {
                    color: '#22BC66', // button colour
                    text: 'Verify your email', // text on the button
                    link: verificationUrl // Link to verify user
                } 
        },
         outro: 'Need help, or have questions? Just reply to this email, we\'d love to help.'
    }
}
}

const forgotPasswordmailgenContent = (username, passwordresetUrl) => {
    return {
        body : {
            name: username,
            intro: 'Reset your password',
            action: {
                instructions: 'To change your password click the button',
                button: {
                    color: '#22BC66', 
                    text: 'reset password',
                    link: passwordresetUrl
                } 
        },
         outro: 'Need help, or have questions? Just reply to this email, we\'d love to help.'
    }
}
}


export {
    mailgen,
    emailVerificationmailgenContent,
    forgotPasswordmailgenContent
}

Use the Functions to Send Emails

const verificationUrl = `${process.env.BASE_URL}/api/v1/users/verify-email/?token=${Token}`
const verificationemailgenContent = emailVerificationmailgenContent(username, verificationUrl)
await mailgen({
     email: email,
     subject: "Verify your email",
     mailgenContent: verificationemailgenContent
});

I hope this helps you. I would be glad to receive your comments, and if you encounter any problems or need help setting this up on your website, just reach out to me. I am happy to assist.

1
Subscribe to my newsletter

Read articles from Indranil Maiti directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Indranil Maiti
Indranil Maiti

I am a MERN stack developer and an aspiring AI application engineer. Lets grab a cup of coffee ad chat.