DEV Community

Cover image for Sending Emails Using Node.js
Bojan Jagetic
Bojan Jagetic

Posted on • Updated on

Sending Emails Using Node.js


In this guide, we'll explore how to send emails using Node.js with the help of Nodemailer, a module for Node.js applications to allow easy email sending.


Before we dive into the code, ensure you have the following prerequisites:

  • Node.js installed on your system
  • An understanding of JavaScript and Node.js basics
  • An email account for sending emails
  • Basic knowledge of Express.js (optional)

Setting Up Nodemailer

First, install the Nodemailer package in your Node.js project using npm or yarn:

npm install nodemailer
npm install multer
Enter fullscreen mode Exit fullscreen mode

Setting environment variables

Then, create a .env file in your project directory to store sensitive information like email credentials:

Enter fullscreen mode Exit fullscreen mode

Replace your_email_host, your_email_port, your_email_username, and your_email_password with your email provider's SMTP details.

Writing the Code

As in this example I am using Express.js we should make router and controller for our API. Lets start with router which will

Setting up Express Router

Now, let's write the Node.js code to send emails. Here's an example function using Express.js for handling email sending requests. In more advanced example I added middelware for validation and token verification, but we can skip it for now. If we want user to be able to attach files when sending email, we can use multer for easy file uploading.

// emailRoutes.js

const express = require('express');
const router = express.Router();
const verifyToken = require('../../middleware/verifyToken');
const upload = require('../../libs/multer');
const { emailSenderValidation, emailContactValidation } = require('../../middleware/mailerValidation');
const { sendNotifyPlainEmail } = require('../../controllers/email/emailController');

// POST route for sending notification emails with plain text'/notify/plain', upload.any('files'), verifyToken, emailSenderValidation, sendNotifyPlainEmail);

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Controller Functions

Now, let's define the controller functions for handling email sending in emailController.js:

const nodemailer = require("nodemailer");
const path = require('path');
const { validationResult } = require('express-validator');
const { generateSimpleEmail, generateContactEmail } = require('./emailGenerator');

async function sendNotifyPlainEmail(req, res) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    const { to, cc, subject, content } = req.body;

    try {
        const transporter = nodemailer.createTransport({
            host: process.env.EMAIL_HOST,
            port: process.EMAIL_PORT,
            secure: true,
            auth: {
                user: process.env.EMAIL_USERNAME,
                pass: process.env.EMAIL_PASSWORD,
            tls: {
                rejectUnauthorized: true,
        const haveAttachments = req?.files ? => {
            return {
                filename: file?.originalname,
                path: path.join('uploads', file?.originalname),
                cid: file?.filename
        }) : false;

        const info = await transporter.sendMail({
            from: '"Admin Test 🚀" <>',
            to: to,
            cc: cc,
            subject: subject,
            text: content,
            html: content,
            attachments: haveAttachments ? haveAttachments : ''
        console.log("Message sent: %s", info);
        res.send({ data: `Email sent to ${to}`, messageId: info.messageId }).status(200);
    } catch (exc) {
        console.error('error happened', exc);
        res.status(400).send({ message: `Message was not delivered to ${to}`, error: exc });

module.exports = { sendNotifyPlainEmail };
Enter fullscreen mode Exit fullscreen mode

Testing API

Ok now we have our API so we want to test it , easiest way to do is with postman or curl, here is the example for curl :

curl --location 'http://localhost:3000/email/notify/plain' \
--header 'x-api-key: 1111111-1111-111-1111-11111' \
--form 'to=""' \
--form 'content="Test 123"' \
--form 'subject="Test Subject"'
Enter fullscreen mode Exit fullscreen mode

After successfully calling our new API we should be able to see response

{"data":"Email sent to","messageId":"<>"}%        
Enter fullscreen mode Exit fullscreen mode


With this code, you can easily send emails using Node.js and Nodemailer. Remember to handle errors gracefully and secure your email credentials properly.

Feel free to customize the code according to your specific requirements and integrate it into your Node.js applications for sending emails effortlessly.

Please leave your comments if you want part 2 where we will be sending email templates using mailer and be sure to checkout original post

Sending Emails Using Node.js

With Node.js, developers have a powerful tool at their disposal for automating tasks, including sending emails.

Top comments (2)

remtech profile image
Remi Osisanya


basskibo profile image
Bojan Jagetic

Thank you very much, tell me if you have some topic for me to cover :)