DEV Community

krishna-Tiwari
krishna-Tiwari

Posted on

Nodemailer and Mailtrap Integration: The Perfect Solution for Easy Email Testing

Introduction

In my experience as a developer, there are many such situations where SMTP services are required. Some of the most common cases are:

  1. While sending verification mail to newly register user.
  2. Sending Once Time Password (OTP) to the user.
  3. To broadcast the mail to all users.
  4. And so on.

That's why iam here today for helping all of you [and it's pleasure also] that, How to setup mailing service with Node js using Nodemailer.

For testing the mailing service I am using Mailtrap.
You can use other services like gmail, outlook but they are premium and costly too.

Nodemailer

Nodemailer is a popular open-source library for sending emails using Node.js. It provides a simple and straightforward way to send email messages programmatically from a Node.js application.

Additionally, Nodemailer supports features like sending bulk emails, handling attachments, embedding images, adding custom headers, and utilizing templates for dynamic content generation.

That's enough to understand. If you have further queries please check out official website of Nodemailer.

Mailtrap

Mailtrap is a popular email testing and debugging tool used by developers and teams during the development and testing stages of their applications. It provides a simulated email inbox environment where you can send test emails without delivering them to real recipients.

If you have futher queries on Mailtrap. Please check out official website of Mailtrap.

I think you understands well about Nodemailer library and Mailtrap testing tool.

Note: You have to sign up for Mailtrap before dive into setup process

Setup Tutorial

1. Create and setup Mailtrap Account

  • Go to the Mailtrap website and signup.

Image description

  • After successfully signed up , you will look the screen liked below :

Image description

  • Click on the email testing and get your secret credentials. Select Nodemailer as the integration option and you will get your secret credentials.

Image description

  • Copy your secret credential code and Now it's oour time to setup Mailtrap with Nodemailer and Express.

Setting up Express server

  • Setup your folder and install packages as mentioned:
npm i express cors nodemailer dotenv mailgen
Enter fullscreen mode Exit fullscreen mode
  • Create a .env file in a root directory. This is the place where we store Mailtrap credentials we get earlier.
EMAIL=<sender's email address>
    USER=<mailtrap user key>
    PASSWORD=<mailtrap password>
Enter fullscreen mode Exit fullscreen mode
  • Main step is to setup server file. In our case name of the file is server.js and write code like as mentioned below:
  import express from 'express';
    import cors from 'cors';
    import dotenv from 'dotenv';
    import nodemailer from 'nodemailer';
    import Mailgen from 'mailgen';

    dotenv.config()   // configure our app to use env variables
    const app = express();
    /** middlewares */
    app.use(express.json());
    app.use(cors());
    app.disable('x-powered-by'); // less hackers know about our stack

    const port = process.env.PORT || 8080;
    /** HTTP GET Request */
    app.get('/', (req, res) => {
        res.status(201).json("Health Check PASS");
    });


    // create reusable transporter object using the default SMTP transport
    const transporter = nodemailer.createTransport({
        host: 'smtp.mailtrap.io',
        port: 2525,
        auth: {
            user: process.env.USER, // generated mailtrap user
            pass: process.env.PASSWORD, // generated mailtrap password
        }
    });
    // generate email body using Mailgen
    const MailGenerator = new Mailgen({
        theme: "default",
        product : {
            name: "Test Email",
            link: 'https://mailgen.js/'
        }
    })
    // define a route for sending emails
    app.post('/send-email', (req, res) => {
        // get the recipient's email address, name and message from the request body
        const { to, name, message } = req.body;
        // body of the email
        const email = {
            body : {
                name: name,
                intro : message || 'Welcome to Test Mail! We\'re very excited to have you on board.',
                outro: 'Need help, or have questions? Just reply to this email, we\'d love to help.'
            }
        }
        const emailBody = MailGenerator.generate(email);
        // send mail with defined transport object
        const mailOptions = {
            from: process.env.EMAIL,
            to: to,
            subject: 'Test Email',
            html: emailBody
        };
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                console.log(error);
                res.status(500).send('Error sending email');
            } else {
                console.log('Email sent: ' + info.response);
                res.send('Email sent successfully');
            }
        });
    });
    // start the server
    app.listen(port, () => {
        console.log(`Server started on port ${port}`);
    });
Enter fullscreen mode Exit fullscreen mode

Testing our email server

The final process and testing our email server,does it actually working or not? Postman api testing tool is useful for performing such API endpoint testing.

Conclusion

Hope this tutorial helps a lot and feel free to leave a comment. You have to perform Api testing and go to Mailtrap dashboard to ensure the application is working or not.

๐ŸŒŸ๐ŸŒŸThank you ๐ŸŒŸ๐ŸŒŸ

Top comments (0)