Nodemailer and Mailtrap Integration: The Perfect Solution for Easy Email Testing
Published: 2023-06-06 16:08:17

# 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.
1. Sending Once Time Password (OTP) to the user.
1. To send the same email to a group of users. [Broadcast 😊]
1. 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](https://nodemailer.com/about/).

## 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](https://mailtrap.io/home).

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](https://mailtrap.io/home) website and signup.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58japd9880sa18qwn3ji.png)
- After successfully signing up, you will look at the screen below : 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcrzvovpqzei7nxlpzuv.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvsvkvdh26g4oxyydl7v.png)

- 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:
```bash
npm i express cors nodemailer dotenv mailgen
```

- Create a .env file in a root directory. This is the place where we store the Mailtrap credentials we get earlier.

```js
EMAIL=<sender's email address>
    USER=<mailtrap user key>
    PASSWORD=<mailtrap password>
```
- 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:
```js
  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}`);
    });
```

### Testing our email server
The final process and testing our email server,does it  actually working or not?  [Postman](https://www.postman.com/) 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 🌟🌟