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.
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.
(If you have Nodejs and Nodemailer module installed, you can skip to execution step)
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)
-. 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.
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
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
// 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
let toMail = '[email protected],[email protected]';
// 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
{ 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' }
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)
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.
sudo npm install -g nodemailer
Netcorecloud's toolkit is the solution to all your email problems.
Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.
Ghanshyam Baviskar
Software Engineer