This article is shared to explain node.js send an email with an HTML template & SMTP through Gmail. You will get standard source code for sending mail using Nodemailer from the localhost or a live server.
As you know that Email is frequently used in web applications to communicate through the internet. It is mainly integrated into the contact us form & signup/ registration form to reach the customer directly, send a notification, & promote products/brands.
You will learn everything related to this topic through some simple steps. But you should have a basic knowledge of Node.js & express for a better understanding. Once you complete this article, you can easily write a script for your website to send an email in node.js.
Nodemailer Module
The Nodemailer Module allows a web application to send an email from the local computer or a server.
The Nodemailer is very simple to create an Email System in Node.js
You can easily install the Nodemailer module using the following NPM command
npm install nodemailer
After installing Nodemailer, You will have to include it in the Node.js app with the following script.
var nodeMailer = require('nodemailer');
Send Email Using Nodemailer
You have to configure the following points to send email using Nodemailer –
- First all, include the Nodemailer module using
require('nodemailer')
and assign it to a variablenodeMailer
- access the transporter from
nodemailer
with the following properties.- host: It accepts the only hostname.
- port: assign port no
587
it, if the security property isfalse
otherwise465
- secure: assign
false
to it, if you send an email from the localhost otherwise true forhttps://
server. - requireTLS: always keep it
true
- user: assign your valid email address to it.
- pass: assign your valid email password to it
- Declare an object
mailMessage
to store mail messages with the following properties- from: It accepts the sender’s email address.
- to: It accepts the receiver’s email address.
- subject: It accepts some subject text.
- text: It accepts plain text for the message.
- Access the
sendMail
fromtransporter
and passmailMessage
& an anonymous function
var nodeMailer = require('nodemailer'); var transporter = nodeMailer.createTransport({ host: 'hostname', port: 587, secure:false, requireTLS:true, auth: { user: 'Enter your email address', pass: 'Enter your emaill password' } }); var mailMessage = { from: 'sender email address', to: 'receiver email address', subject: 'Enter subject Text', text: 'Enter Email Message' }; transporter.sendMail(mailMessage, function(error, data){ if (error) { console.log(error); } else { console.log('Email sent: ' + data.response); } });
Nodemailer multiple recipients
Nodemailer allows us to assign multiple recipients. So, you can assign multiple emails addresses to the property to
with separated by a comma ,
var mailMessage = { from: 'sender email address', to: 'reciever email address 1, reciever email address 2, reciever email address 3,..', subject: 'Enter mail subject', text: 'Enter Mail Message' }
Node.js Send Email with HTML template
If you need to send an email with an HTML template, you will have to declare html
instead of text
property with HTML tag & plain text.
var mailMessage = { from: 'sender email address', to: 'receiver email addres', subject: 'Enter mail subject', html: '<h1Some heading text here</h1><p>Some paragraph text here</p>' }
Node.js send an Email through Gmail
If you need to use a Gmail account to send an email using node.js, you have to assign it only smtp.gmail.com
to the host
property. The remaining previous code will be the same.
You have to configure a basic setting in a google account if you send an email from a less secure server like or localhost. So, go through the following steps –
- First of all, Open Google Account and sign in with a Gmail account that is assigned to auth property.
- Click the security navigation link that remains at the left sidebar.
- Scroll down and find out the Less secure app access box section.
- Click turn on access and turn on with switch toggle button.
Now, Let’s understand it from the next steps with an example. once you learn it, you will be able to integrate a mailing system into your project.
How to send Email in Node.js
From this step, We will send an email from an HTML form in Node.js & expressjs. after learning it, you can easily configure it with the signup or contact us form. So, follow all the given steps
1. Install Node.js and Express Application
First of all, you have to install Node.js and express application. After installing them, you will get the following folder structure.
myapp/ |__bin |__node_modules |__public |__routes/ | |__email-route.js | | |__views/ | |__email-form.ejs | | |__app.js |__database.js |__package-lock.json |__package.json
2. Install Nodemailer Module
Install Nodemailer Module by running the command –
npm install nodemailer
3. Create an Email form
Create a file email-form.ejs
in the views folder and write the following HTML code to create an email form. Here the ejs is a template engine. This form must contain two attributes –
- method=”post” – It will send secure email
- action=”send-email” – It will redirect to the route
send-email
.
File Name – email-form.ejs
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><%= title %></title> <style> * { box-sizing: border-box;} .user-detail { height: 100vh; border: 2px solid #f1f1f1; padding: 16px; background-color: white; width: 30%;} input, textarea{ width: 100%; padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1;} input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none;} button[type=submit] { background-color: #434140; color: #ffffff; padding: 10px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; opacity: 0.9; font-size: 20px;} label{ font-size: 18px;;} button[type=submit]:hover { background-color:#3d3c3c;} </style> </head> <body> <!--====form section start====--> <div class="user-detail"> <h2>Send mail with nodejs</h2> <hr> <form action="/send-email" method="POST"> <label>To</label> <input type="text" placeholder="Receiver Email" name="to" required > <label>Subject</label> <input type="text" placeholder="Enter Email Address" name="subject" required > <label>Message</label> <textarea placeholder="Enter Full Country" name="message" required > </textarea> <button type="submit">Send and Email</button> </div> </div> <!--====form section start====--> </body> </html>
4. Write Send Email Script
Create a route file email-route.js
in the routes folder and configure the following points to write the send email script –
- Include express package using
require('express')
and assign it to a variableexpress
. - Access router method from the express as
express.Router()
and assign it to a variablerouter
. - Include Nodemailer module using
require('nodemailer')
and assign it to a variablenaodemailer
. - Create a
send-email
route using the get method and load email form fileemail-form
. - Also, create another
send-email
route using the post method and write send email script - At last, export router module using
module.exports = router;
File Name – email-route.js
var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); // load email form router.get('/send-mail', function(req, res, next) { res.render('mail-form', { title: 'Send Mail with nodejs' }); }); // This route will work after submit the form router.post('/send-email', function(req, res){ var receiver = req.body.to; var subject = req.body.subject; var message = req.body.message; var transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure:false, requireTLS:true, auth: { user: 'codingstatus@gmail.com', // enter your email address pass: '********' // enter your visible/encripted password } }); var mailOptions = { from: 'codingstatus@gmail.com', to: receiver, subject: subject, text: message }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email was sent successfully: ' + info.response); } }); res.render('mail-form', { title: 'Send Mail with nodejs' }); }) module.exports = router;
5. Include Route File in app.js
In the previous step, we have created a route file email-route.js
. Now, you have to include it in the app.js
using the following line of code –
File Name – app.js
var emailRouter = require('./routes/email-route'); app.use('/', emailRouter);
6. Execute Send Email Script
At last, you can execute the send email script by doing the following steps –
- Start node.js using the command
npm start
- Open the following URL in your browser.
http://localhost:3000/send-email
- Enter a receiver email address, subject & message in the form.
- Submit the form to send an email.
After doing the above steps, an email will be sent successfully
Tutorial Summary
Dear developers, I hope you have understood the above script, Now you can easily send an email using Node.js & expressjs.
If you have any questions regarding Node.js. You can directly ask me through the below comment box. Even share this tutorial with your friends.