To send an email in Node.js, use the “nodemailer” module. The nodemailer is a module that allows you to send emails easily without hassle. It uses a Simple Mail Transfer Protocol (SMTP) for sending email messages between servers. Most email systems that send mail over the Internet support SMTP-based sending.
Here is the step-by-step guide to send an email in Node.js.
Step 1: Create a project and configure it.
Create a project directory, and type the following command in it.
npm init
We are going to use a nodemailer package for sending email. Also, we are using an express web framework, so let us download both.
npm install --save nodemailer express
To get rid of the server every time, we use one package called the nodemon server.
npm install nodemon --save-dev
In the root directory, create one js file called server.js
// server.js
var express = require('express'),
path = require('path'),
nodeMailer = require('nodemailer');
var app = express();
var port = 3000;
app.listen(port, function(req, res){
console.log('Server is running at port: ',port);
});
This is just a boilerplate to start our project. One thing we need to do is that we need to modify the start script in a package.json file.
// package.json
"scripts": {
"start": "nodemon server"
},
So, when we have to start the node server, we need to write the following command.
npm start
If we change the file, then it will restart the server automatically.
Step 2: Use EJS as a templating engine.
We must install a templating engine called ejs(embedded javascript) by typing the following command.
npm install --save ejs
Create one directory in the root folder called the public.
// server.js
app.set('view engine', 'ejs');
app.use(express.static('public'));
We are setting up an ejs templating engine for our application. Also, we are serving static files from the public directory.
We also need to create another folder called views in the root folder. In that, create one file called index.ejs.
// index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nodemailer Email Example</title>
</head>
<body>
<div class="container">
<div class="jumbotron">
Sending Email in Node.js
</div>
</div>
</body>
</html>
We have used the Bootstrap CSS class here, so we must include the library in the public folder.
<link rel="stylesheet" href="bootstrap.min.css">
Also, create one route for the home page by typing the following code.
// server.js
app.get('/', function (req, res) {
res.render('index');
});
If you have not started the server yet, please initiate the server by the following command.
npm start
It will start at port 3000. Switch to the URL: http://locahost:3000
Step 3: Create a basic bootstrap form.
Create one bootstrap form to send the email. We are going to put that form in the index.ejs file.
<!-- index.ejs --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Nodemailer Email Example</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <div class="container"><br /> <h1>Send The Email</h1><br /> <form action="/send-email" method="post"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="to">To:</label> <input type="email" class="form-control" name="to"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="subject">Subject:</label> <input type="text" class="form-control" name="subject"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="body">Body:</label> <textarea cols="5" rows="5"class="form-control" name="body"></textarea> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success">Send</button> </div> </div> </form> </div> </body> </html>
Our Primary form will look like this. Now, set the post action of the form.
<!-- index.rjs --> <form action="/send-email" method="post">
However, we need to install the body-parser package to get all the field data on the server side.
Step 4: Write the code that sends the email.
npm install body-parser --save
Use this package in our express framework by using the following code.
// server.js var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json());
The next step is to create a route for the post request sent by form and handle its data. So, our final server.js file will look like this.
// server.js var express = require('express'), path = require('path'), nodeMailer = require('nodemailer'), bodyParser = require('body-parser'); var app = express(); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); var port = 3000; app.get('/', function (req, res) { res.render('index'); }); app.post('/send-email', function (req, res) { let transporter = nodeMailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: 'xxx@xx.com', pass: 'xxxx' } }); let mailOptions = { from: '"Krunal Lathiya" <xx@gmail.com>', // sender address to: req.body.to, // list of receivers subject: req.body.subject, // Subject line text: req.body.body, // plain text body html: '<b>NodeJS Email Tutorial</b>' // html body }; transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); res.render('index'); }); }); app.listen(port, function(){ console.log('Server is running at port: ',port); });
Here, I have shown you to send the email via Gmail. You can use any other host. First, you need to grab their API keys.
If you use Gmail, please update your credentials in the options object.
If an email is successfully sent, our form page index.ejs will return; otherwise, check the console in the terminal. You will get an error over there.
This is an example of Sending an email using a nodemailer.
That’s it.
Xander
Hello,
I am trying to send files and images using nodemailer.
I know I can do attachments: from nodemailer but I want to be able to upload something using and then being able to do req.body.something.
People say I need to use multer for this and enctype=”multipart/formdate” in the tag.
This first of all would upload it to my server and secondly I can’t seem to get that work either.
I am already stuck on trying to get this to work for quite a while so I was wondering if you could make a tutorial on this or help me out when ever you have some spare time.
I can also give you a copy of my code I am using at the moment and all the modules I have on there.
I am sorry if I am asking to much from you but I am stuck for a while now and couldn’t find a good or clear answer for some beginning node.js developer.
-A desperate person
Wayne
Hi,
Trying this but all I get in the console is { submit: ‘ ‘ }
app.post(‘/send-email’, function (req, res) {
console.log(req.body);
});
Any help would be awesome.
jaay
@Krunal
Hi, i have been searching the same using Angular 2.! Can you pls post tutorial on how to send mail using Angualr 2
J4GD33P 51NGH
What if two step verification is enabled for sender email?
Meer Hama
it works locally but it does not work when i deploy it
Mudrak Patel
Hi Krunal, nice article. I am working on a MEAN stack project. I have a contact form that has 4 fields: to, from, subject and body. The contact form has a button that when clicked should send email to the email address written in the “to” field. Now I DONOT want to include my email password in any file in my entire project. Is there any way to do this?
Amit
you can put it in the .env file and put .env file into the .gitignore file so that when you push your code,
your credentials will not get posted.
raju vais
hello,
thanks for it
if i am not using gmail service instead of that i am using info@motivesite.com
so what will be host name and port
please help me
Greg Wilson
Awesome stuff!! This should help me to get email notifications sending for my React – Node app!!