Send an email using Nodemailer and Gmail in Node.js Express.js

Nodemailer
Nodemailer is a module for Node.js applications to send emails between different email hosts using different transport methods. It is a single module with zero dependencies with a heavy focus on security (TLS/STARTTLS). It supports Unicode and Windows. We can also send text and HTML content.
Migrating Nodemailer from v2 to v3 has dropped some features that were available in v2 and introduced some new ones.
- All dependencies were dropped
- All templating is gone
- OAuth2 authentication
- Delivery status notification
- Calendar Events
SMTP
What is SMTP? SMTP is part of the application layer of the TCP/IP protocol. Using a process called “store and forward”, SMTP moves your email on and across networks. It works closely with something called the Mail Transfer Agent (MTA) to send your communication to the right computer and email inbox.
It is used as a transporter in Nodemailer for delivering messages between different email hosts as a protocol. Even if every Gmail delivery provider mainly focused on their API based sending, but they also support SMTP based sending. APIs might have more features but using the SMTP method, we only need to change the configuration options to replace one provider with another. It is easy to implement compared to other methods.
More about SMTP — refer: Nodemailer SMTP
Install Nodemailer from npm
npm install nodemailer
Install SMTP transport module for Nodemailer with npm
npm install nodemailer-smtp-transport
Require to your script
var nodemailer = require(‘nodemailer’);var smtpTransport = require(‘nodemailer-smtp-transport’);
Create a Nodemailer transport object
var transporter = nodemailer.createTransport(smtpTransport(options))
Here, options define connection data and it includes
options.port
Port to connect to (defaults to 25 or 465)
options.host
Hostname or IP address to connect to (defaults to ‘localhost’). If you are using SMTP with Google, you have to put ‘smtp.gmail.com’ as a host.
options.secure
It defines if the connection should use SSL (if true) or not (if false). if you are connecting to port 465 it should be true. For port 587 or 25 keep it false.
options.auth
It defines authentication data,
Type — indicates the authentication type, defaults to ‘login’, other option is ‘oauth2’
user — Username
- pass — Password for the user if normal login is used
options.ignoreTLS
It turns off STARTTLS support if true
options.name
The optional hostname of the client, used for identifying the server
options.localAddress
It is the local interface to bind to network connections
options.connectionTimeout
How many milliseconds to wait for the connection to establish. (default is 2 minutes)
options.authMethod
It defines the preferred authentication method, eg. ‘PLAIN’
options.tls
It defines additional options to be passed to the socket constructor, eg. {rejectUnauthorized: true}
Before you use your SMTP Gmail server, make sure that ‘less secure’ is on in your Gmail settings.
Refer: Google Supports
- Setup Nodemailer
let transporter = nodemailer.createTransport(smtpTransport({
service: ‘gmail’,
host: ‘smtp.gmail.com’,
auth: {
user: ‘user.gmail’,
pass: ‘user.password’
}
}));
2.1 Sending plain text
const mailOptions = {
from: ‘sender.gmail’,
to: ‘receiver.email’,
subject: ‘subject’,
text: ‘message‘
};
2.2 Sending HTML content
const mailOptions = {
from: ‘sender.gmail’,
to: ‘receiver.email’,
subject: ‘subject’,
html: ‘message‘
};
3. Sending mail and get sent message
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
Example Code
- Setup a form to get details
<form role="form" action="/send-mail" method="POST">
<div class="form-group">
<label for="to">To</label>
<input type="text" class="form-control" id="to"
name="to" placeholder="Receiver Email" required>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject"
name="subject" placeholder="Subject" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message"
name="message" placeholder="Message" required></textarea>
</div>
<div class="text-center">
<button type="submit" id="submit" name="submit" class="btn
btn-primary btn-sm">Send</button>
</div>
</form>
2. Get ‘send-mail’ route and send email
//require
var express = require("express"),
router = express.Router(),
smtpTransport = require('nodemailer-smtp-transport');//setup nodemailer
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'user.email',
pass: 'user.password'
}
}));
//get route to send mail, from form
router.post("/send-mail", function(req,res){
var to = req.body.to,
subject = req.body.subject,
message = req.body.message; //options
const mailOptions = {
from: ‘example@gmail.com’,
to: to, // from req.body.to
subject: subject, //from req.body.subject
html: message //from req.body.message }; //delivery
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
});
module.exports = router;