How to send email with Node.js?

Published on 2019-09-20ยท Updated on 2023-09-06

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

Nodejs is a server-side javascript runtime environment built on chrome v8 engine. It allows developers to use javascript on the server-side.

Nodejs is cross-platform. It is available for Windows, Linux and Mac. As a part of this tutorial, Windows 10 and Nodejs 10.16.3 stable version is used to code and send mail.

Prerequisites

  • A working windows 10 machine.
  • Nodejs libraries installed
  • Nodemailer NPM module installed.

Installation

(If you have Nodejs and Nodemailer module installed, you can skip to execution step)

  1. Install Node Js: Visit https://nodejs.org/en/ to download the NodeJs MSI installer. I am using version 10.16.3 for this tutorial.
  2. Double click on the MSI file to start the installer, then click 'Run'. Like any other installation on windows, you have just to click the "Next" button several times to complete the installation ๐Ÿ™‚.
  3. Read and accept the terms in the license agreement.
  4. Select the default location for Nodejs (remember this location to verify the installation).
  5. Click on install and finish the installation.
Verify Nodejs installation working properly:

1. Open the Nodejs installation directory, which we had selected at the time of installation. In our case it is C:\Program Files\nodejs. If you don't remember the installation directory, go to C: drive and find Program Files. In this directory, you should find the Nodejs directory, as it is the default location. Here, you see the Nodejs application, double click it. A command prompt will appear.

2. Let's try basic javascript to test our nodejs installation.

var message = `Hello world`
console.log(message)

Nodemailer module Installation :

-. Nodejs comes with NPM. NPM(Node package manager) is the default package manager for Nodejs. Nodejs does not include any preinstalled module or library to send emails. You have to install third-party modules like NodeMailer or AlphaMail using NPM.

  1. To begin with, our project to send an email, let's create a folder named send_emails, press shift and right-click in the folder. You should have an option 'Open PowerShell Window Here' click on this option. Windows PowerShell will appear.
  2. In case you don't find the option to open PowerShell from this folder. Just copy the absolute path of the folder, open PowerShell from windows start menu and change directory in Powershell.
  3. Create a package.json file to install nodemailer from NPM. In PowerShell window, type following npm command:
    npm init
  4. In package.json file, we have to:
    undefinedundefinedundefinedundefined

A package.json file gets created in your project folder.

{
  "name": "send_emails",
  "version": "1.0.0",
  "description": "'A simple app to send emails from nodejs'",
  "main": "mailer.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "author name",
  "license": "ISC"
}

5. Execute following npm command to install nodemailer in the project. This will also add an entry to package.json file in the dependency array.

npm install --save nodemailer

Execution

1. To send email using Gmail as a service from third-party apps like our nodejs app, we have to enable 'Allow less secure apps' in Gmail. Login in your Gmail account and navigate to "https://myaccount.google.com/lesssecureapps" and enable the 'Allow less secure apps'.

2. Now create a file mailer.js where you're going to write code to send emails.

3. In mailer.js, include nodemailer:

// include nodemailer
const nodemailer = require('nodemailer');

4. Declare variables

  • fromMail: sender email address
  • toEmail: recipent email address
  • subject: email subject line
  • text: email body text
// declare vars,
let fromMail = 'Enter sender email address';
let toMail = 'Enter recipient email address to which email will be sent';
let subject = 'Enter subject line here';
let text = "Enter email content." 

5. Define a transporter object. Make sure to replace the account_password with your Gmail password.

const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
    user: fromMail ,
    pass: 'account_password'
}
});

6. Set up message options (who sends what to whom)

// email options
let mailOptions = {
from: fromMail,
to: toMail,
subject: subject,
text: text
};

7. Deliver the mail options to the sendMail method of transport object created previously:

// send email
transporter.sendMail(mailOptions, (error, response) => {
if (error) {
    console.log(error);
}
console.log(response)
});

node mailer.js
  1. Email sent to the recipient's email address.
    You can assign multiple email addresses to the Mail variable. Here is a sample to send email to multiple emails:
let toMail = '[email protected],[email protected]';

Working code:

// include nodemailer
const nodemailer = require('nodemailer');
// declare vars
let fromMail = '[email protected]';
let toMail = '[email protected]';

// let toMail = '[email protected],[email protected]';

let subject  = 'An email using nodejs app';
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." 

// auth
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'account_password'
    }
});

// email options
let mailOptions = {
    from: fromMail,
    to: toMail,
    subject: subject,
    text: text
};

// send email
transporter.sendMail(mailOptions, (error, response) => {
    if (error) {
        console.log(error);
    }
    console.log(response)
});

You can download the working code from the below GitHub link:
https://github.com/ghansh22/email_using_nodejs.git

Errors:

{ Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials w11sm630141pfd.116 - gsmtp
    at SMTPConnection._formatError (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:781:19)
    at SMTPConnection._actionAUTHComplete (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:1516:34)
    at SMTPConnection._responseActions.push.str (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:554:26)
    at SMTPConnection._processResponse (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:940:20)
    at SMTPConnection._onData (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:746:14)
    at TLSSocket.SMTPConnection._onSocketData (C:\Users\light\Desktop\send_emails\node_modules\nodemailer\lib\smtp-connection\index.js:189:46)
    at TLSSocket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at TLSSocket.Readable.push (_stream_readable.js:224:10)
  code: 'EAUTH',
  response:
   '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8  https://support.google.com/mail/?p=BadCredentials w11sm630141pfd.116 - gsmtp',
  responseCode: 535,
  command: 'AUTH PLAIN' }
  • We have to enable the Gmail service to use it in third-party apps. In case we miss to do so, we may face such error. To resolve this error just login in Gmail account and enable less secure apps using this link https://myaccount.google.com/lesssecureapps
  • Another reason for this error can be the wrong email(sender) or password. Please check the email address and password. Also, check whether you entered any space in the email/password string mistakenly.
internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'nodemailer'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\light\Desktop\send_emails\mailer.js:2:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
  • If your nodemailer module installation failed, you might face this error. To resolve this error, go to installation steps, and install a nodemailer.
  • You can also install nodemailer globally using the following command.
npm install -g nodemailer
npm WARN checkPermissions Missing write access to /usr/lib/node_modules
/usr/lib
โ””โ”€โ”€ [email protected] 

npm ERR! Linux 3.10.0-957.10.1.el7.x86_64
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "nodemailer"
npm ERR! node v6.16.0
npm ERR! npm  v3.10.10
npm ERR! path /usr/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access

npm ERR! Error: EACCES: permission denied, access '/usr/lib/node_modules'
npm ERR!     at Error (native)
npm ERR!  { Error: EACCES: permission denied, access '/usr/lib/node_modules'
npm ERR!     at Error (native)
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/lib/node_modules' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.
  • If you are trying to install a nodemailer globally using npm, you will get this error. Use sudo with install command to resolve this.
sudo npm install -g nodemailer

Grade My Email
Check your spam now?

Netcorecloud's toolkit is the solution to all your email problems.

Ghanshyam Baviskar

Software Engineer

You can also explore

Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.

Deploy emails that are
screenshot worthy!

Stop settling for static emails - use Netcore's platform to create dynamic, interactive emails that convert.
Let's Deploy
Get Started Now