Skip to main content
sendmail-using-nodemailer

Nodejs Send Email Using Nodemailer

Email is used to send notifications or information to the user. This Nodejs tutorial help to send email using nodemailer. You can send mail as plain text, HTML body and email with attachments. I will demonstrate all flavors of email using node Nodemailer.

The Nodemailer is an npm package and module for Node.js applications to allow easy as sending an email. It is the most popular email package for Node.js.

I am using Mailtrap server to test mail, It’s a fake email SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming.

Send Email in Nodejs

Let’s create a simple nodejs application that is running into the Expressjs server. I ll create Rest API that will send mail to the target email id, Since I am using a fake email server. You need to replace credentials as per your SMTP server credentials.

Created a ‘nodejs-send-email’ folder that holds all these tutorial files.

We will create a package.json file and write the below code into this file –

{
  "name": "node-mysql",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": {
    "name": "Adam"
  },
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "nodemailer": "^6.3.1"
  }
}

Now, Run npm command to install nodejs dependency packages.

$nodejs-send-email> npm install

Above command installed express, body-parser and nodemailer node modules as dependencies. The nodemailer is responsible to send mail, rest of them change accordingly as your requirement.

Lets’ Create server.js file and add the below code into this file, I have imported the nodemailer package into the application. We need userid and pass of mailtrap account, You can get a username and pass on successful registration.

var express  = require('express');
var app      = express();
var bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

var port     = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json

app.listen(port);
console.log("App listening on port : " + port);
let transport = nodemailer.createTransport({
    host: 'smtp.mailtrap.io',
    port: 2525,
    auth: {
       user: 'userid',
       pass: 'pass'
    }
});

Send Plain Email in Nodejs

We have configured the node-mailer module, I will create ‘/api/send_plain_mail’ endpoints, It’s an HTTP get a call to send mail from nodejs application.

You can also read Node js Rest Api to Add, Edit and Delete Record from MySQL Using Express.

//send mail
app.get('/api/send_plain_mail', function(req, res) {
		console.log('sending email..');
		const message = {
	    from: '[email protected]', // Sender address
	    to: 'to emailId',         // recipients
	    subject: 'test mail from Nodejs', // Subject line
	    text: 'Successfully! received mail using nodejs' // Plain text body
	};
	transport.sendMail(message, function(err, info) {
	    if (err) {
	      console.log(err)
	    } else {
	      console.log('mail has sent.');
	      console.log(info);
	    }
	});
});

How To Send HTML Email in Nodejs

We can also send HTML body email using nodemailer. Earlier, We have tried plain text email using ‘text’ properties.to send an HTML email, You need to pass body HTML text to 'html' property.

const message = {
	    from: '[email protected]', // Sender address
	    to: 'to emailId',         // recipients
	    subject: 'test mail from Nodejs', // Subject line
	    text: 'Successfully! received mail using nodejs' // Plain text body
	}

Send Email With Attachment in Nodejs

We can also send an email with attachments in nodejs. Sometimes, We need to send an email with attachments like invoices, pictures, spreadsheets for work, or videos.

const message = {
	    from: '[email protected]', // Sender address
	    to: 'to emailId',         // recipients
	    subject: 'test mail from Nodejs', // Subject line
	    text: 'Successfully! received mail using nodejs', // HTML body
attachments: [
        { // Use a URL as an attachment
			  filename: 'airplane.png',
			  path: 'https://homepages.cae.wisc.edu/~ece533/images/airplane.png'
		  }
		]
	}

Conclusion:

We have created a nodejs project from scratch and added nodemailer package.This tutorial described step-by-step send mail using nodejs. We have sent mail as a plain text body, html body and email with the attachment.

Leave a Reply

Your email address will not be published. Required fields are marked *