DEV Community

krishna-Tiwari
krishna-Tiwari

Posted on • Edited on

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

Introduction

As a developer, I have experienced many such situations where SMTP [email services] services are required. Some of the most common cases are:

  1. While sending verification mail to newly registered users.
  2. Sending Once Time Password (OTP) to the user.
  3. To send the same email to a group of users. [Broadcast ๐Ÿ˜Š]
  4. And so on.

I am here today to assist all of you [and it's a pleasure also] with, How to set up a mailing service with Express and Nodemailer.

For the testing purpose of 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 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 the 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 further queries on Mailtrap. Please check out the official website of Mailtrap.

I think you have a good understanding of the Nodemailer library and Mailtrap testing tool.

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

Setup Tutorial

1. Create and set Mailtrap Account

  • Go to the Mailtrap website and signup.

Image description

  • After successfully signing up, you will look at the screen 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 the Mailtrap credentials we get earlier.
EMAIL=<sender's email address>
    USER=<mailtrap user key>
    PASSWORD=<mailtrap password>
Enter fullscreen mode Exit fullscreen mode
  • The main step is to set up the server file. In our case name of the file is server.js and write code 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)