Nodemailer is a module used to send emails using Nodejs applications. It supports Node.js version 6 and further. Nodemailer is licensed by MIT, to use it first we have to install using npm.
// Installing package locally
C:\Users\Your Name>npm install nodemailer
After installing, include it in any application using require( ) function.
var nodemailer = require('nodemailer');
To send email first we need a transporter object.
// Syntax
var transporter = nodemailer.createTransport(transport[, defaults])
//define transport variable inside createTransport() function
var transporter = nodemailer.createTransport({
service: 'gmail', //name of email provider
auth: {
user: '[email protected]', // sender's gmail id
pass: 'sender password' // sender password
}
});
where
- Transporter is an object to send mail.
- Transporter is the transport configuration object, connection URL or a transport plugin instance.
- The default is an object that defines default values for mail options.
Using sendMail( ) function of transporter object we can send the mail.
// Syntax
transporter.sendMail(data[, callback(err, info)])
// here mailOptions define as data of sendMail( )function
var mailOptions = {
from: '[email protected]', // sender's gmail
to: '[email protected]' , // receiver's gmail
subject: 'Sending Email using Node.js', //subject
text: 'That was easy!' //message Description
};
where,
- Data defines the mail content.
- The callback is an optional callback function to run once the message is delivered or failed.
- err is the error object if message failed.
- info includes the result, the exact format depends on the transport mechanism used.
Topics Covered
- Send email using simple Node.js File.
- Send email using HTML Form and Node.js File.
- Send the email with the attachment.
Send email using simple Node.js File
Now it’s time to send emails from your server using simple js file.
Use the username and password from your selected email provider to send an email (here we are using Gmail).
Save the file as mail_send.js
//save file as mail_send.js
// require the node module for sending the mail
var nodemailer = require('nodemailer');
// create reusable transporter object using the gmail transport
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'sender’s password'
}
});
var mailOptions = {
from: '[email protected]', // sender's gmail
to: '[email protected]' , // receiver's gmail
subject: 'Sending Email using Node.js', //subject
text: 'That was easy!' //message Description
};
//send mail using transport object’s sendMail() function
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Run Command:
c:\Users\Your Name>node mail_send.js
Result:
See the result in the terminal (you will get something like this).
c:\Users\Your Name>Email sent: 250 2.0.0 OK 1514477024 q74sm68457667pfd.134 - gsmtp
To send an email to multiple receivers, add all receiver’s email id to, “to” property of the mailOptions object, separated by a comma.
Send email using HTML Form and Node.js File.
First Create a mailsend.html file using following code in public folder.
<!-- save file as mailsend.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mail Sending Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<style>
div.frm {
margin: 0px auto;
}
</style>
</head>
<body>
<div class="container">
<div class="frm">
<h2>Mail Sending Form</h2>
<form action="/mailing" method="POST">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="demail" style="width:400px" required>
</div>
<div class="form-group">
<label for="pwd">Subject</label>
<input type="text" class="form-control" id="sub" placeholder="Enter subject" name="dsub" style="width:400px" required>
</div>
<div class="form-group">
<label for="msg">Message</label>
<textarea class="form-control" id="dmsg" name="dmsg" style="width:400px" cols="40" rows="5" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
</div>
</body>
</html>
Next, create a mailsendform.js file using following code in the root folder.
// save file as mailsendform.js
var nodemailer = require('nodemailer');
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
http.createServer(function (req, res) {
if (req.url === "/") {
fs.readFile("./public/mailsend.html", "UTF-8", function (err, html) {
res.writeHead(200, { "Content-type": "text/html" });
res.end(html);
});
}
if (req.method === "POST") {
var data = "";
req.on("data", function (chunk) {
data += chunk;
});
req.on("end", function (chunk) {
var q = querystring.parse(data);
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]', // sender's gmail id
pass: 'sender password' // sender password
}
});
var mailOptions = {
from: '[email protected]', // receiver's gmail id
to: q.demail, // data coming from form
subject: q.dsub, // data coming from form
text: q.dmsg // data coming from form
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
res.end("Mail sent successefully");
console.log('Email sent: ' + info.response);
}
});
});
}
}).listen(3000);
Run Command:
c:\Users\Your Name>node mailsendform.js
Go to browser and type:
http://localhost:3000
Send email with attachment
First Create a mailsendattch.html file using following code in public folder.
<!-- save file as mailsendattch.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mail Sending Page with attachement </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<style>
div.frm {
margin: 0px auto;
}
</style>
</head>
<body>
<div class="container">
<div class="frm">
<h2>Mail Sending form</h2>
<form action="/mailing" method="POST">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="demail" style="width:400px" required>
</div>
<div class="form-group">
<label for="pwd">Subject</label>
<input type="text" class="form-control" id="sub" placeholder="Enter subject" name="dsub" style="width:400px" required>
</div>
<div class="form-group">
<label for="msg">Message</label>
<textarea class="form-control" id="dmsg" name="dmsg" style="width:400px" cols="40" rows="5" required></textarea>
</div>
<div class="form-group">
<label for="fileld">File</label>
<input type="file" class="form-control" id="fileid" name="dfile">
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
</div>
</body>
</html>
Next, create a mailsendattch.js file using following code in the root folder.
// save file as mailsendattch.js
var nodemailer = require('nodemailer');
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url === "/") {
fs.readFile("./public/mailsendattch.html", "UTF-8", function (err, html) {
res.writeHead(200, { "Content-type": "text/html" });
res.end(html);
});
}
if (req.method === "POST") {
var data = "";
req.on("data", function (chunk) {
data += chunk;
});
req.on("end", function (chunk) {
var q = querystring.parse(data);
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]', // sender's gmail
pass: 'sender passwprd' // sender's password
}
});
var mailOptions = {
from: '[email protected]', // sender's gmail
to: q.demail, // data coming from form
subject: q.dsub, // data coming from form
text: q.dmsg, // data coming from form
attachments: [{ // file on disk as an attachment
filename: q.dfile, // name of the file attach
path: q.dfile
}]
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
res.end("Mail sent successefully");
console.log('Email sent: ' + info.response);
}
});
});
}
}).listen(3000);
Run Command:
c:\Users\Your Name>node mailsendattch.js
Go to browser and type:
http://localhost:3000
Learn More-