23

Nodejs Send Email Using Nodemailer

 4 years ago
source link: https://www.js-tutorials.com/nodejs-tutorial/nodejs-send-email-using-nodemailer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Email is use to send notification or information to the user.This nodejs tutorial help to send email using nodemailer . You can send mail as a plain text, HTML body and email with attachment.I will demonstrate all flavors of email using node Nodemailer.

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

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

Table of Contents

    • Send Plain Email in Nodejs
    • How To Send HTML Email in Nodejs
    • Send Email With Attachment

Send Email in Nodejs

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

Created ‘nodejs-send-email’ folder that hold all this tutorial files.

We will create package.json file and write 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 added 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 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 node-mailer module, I will create '/api/send_plain_mail' end points, Its a HTTP get 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 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: '<p>Successfully! received mail using nodejs</p>' // Plain text body
	}

Send Email With Attachment

We can also send email with attachment in nodejs. Sometimes, We need to send email with attachment like invoice, 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: '<h2>Successfully! received mail using nodejs</h2>', // 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 send mail as a plain text body, html body and email with attachment.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK