How to send emails in your Node.js app using Nodemailer and Mailtrap

I am a software developer and project manager; passionate about solving problems through IT.
Search for a command to run...

I am a software developer and project manager; passionate about solving problems through IT.
Soon I'll be using Node.js to create a project that will need to send personal emails to customers.
I just bookmarked this. Thanks for sharing!
The realm of Brain-Computer Interfaces (BCIs) is rapidly evolving, promising to revolutionize human-computer interaction. From medical applications like restoring mobility and communication to entertainment and cognitive enhancement, BCIs are poised ...
If you’re into Technical Writing or a member of any tech community, you’ve probably heard of the buzzword “DevRel.” It’s strange and confusing how so many job roles have been introduced into the world during this information age, and even confusing t...
Web scraping is an automatic method to obtain large amounts of data from websites. The data is largely unstructured and can be further refined. In this article, we will be testing the desktop application Scrape Any Website as an exercise for the HNGi...
Java is a multi-platform, object-oriented, and network-centric language. Spring Boot is an open-source Java-based framework used to create a microservice. It provides a good platform for Java developers to develop stand-alone and production-grade spr...
Going straight to coding without a ‘definite’ idea of what your app should look and feel like is very risky and can lead to unnecessary rework. It’s therefore necessary to plan a roadmap or process flow. This does not mean you have to have it all pla...
In this article, we will be covering the basics of sending emails from your Node.js using nondemailer and mailtrap.
Now that that's set-up. Let's get to it
1) Create a folder that you want to work in and cd into it
2) Create a package.json file by running npm init . Provide answers to the question as seen in the picture below

3) Install the following dependencies- body-parser, dotenv, express
4) Install nodemon as a dev dependency
5) Edit your package.json file and add the following to your scripts
"start": "node server.js",
"dev": "nodemon server.js"
Set up your index.js file
const bodyParser = require('body-parser');
const express = require('express');
const dotenv = require('dotenv');
const app = express();
dotenv.config();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
module.exports = { app };
.env fileThe folder structure

const nodemailer = require('nodemailer');
module.exports = {
sendEmail: async (options) => {
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
const message = {
from: `${process.env.SENDER_NAME} <${process.env.SENDER_EMAIL}>`,
to: options.email,
subject: options.subject,
html: options.message,
};
await transporter.sendMail(message);
},
};
Create your email body. This can either be a snipped of HTML code (e.g. <p> Hello there </p>) or an entire HTML page. We'll be using the later.
exports.message = async () => {
const html = `<!DOCTYPE html> <head> <title> Greetings</title> </head>
<body> <p> Hello there. How are you? </p></body>
</html>`;
return html;
};
Create your POST route that handles that wraps everything up.
We'll use this in the index.js file
Start by importing the required functions
const { sendEmail } = require('./Utils/emailSender');
const { message } = require('./Utils/emailTemplate');
The route
app.post('/', async (req, res, next) => {
const { email } = req.body;
try {
const result = await sendEmail({
email,
subject: 'Hello World!',
message: await message(),
});
res.status(200).json({ status: 'Email sent', result });
} catch (err) {
res.send('Email not sent');
// next(err);
}
});
Let's test this on Postman.

Let's check mailtrap for the email

Now that you've learned how to send emails, you can try in your project.
You can also check out the full source code here
If you like this article, feel free to comment and share. You can also reach out to me on Twitter | LinkedIn | Github
Ciao👋🏼