Send Emails with Node.js the Easy Way

Sending emails by using Node.js is a simple process. It is commonly achieved by using the nodemailer npm package.
What is nodemailer?
Nodemailer is an npm package which is used to send emails from a server by providing an API for constructing and sending emails.
Installation of nomailer
To use nodemailer, open your terminal and use the command:-
npm i nodemailer
After completing the installation of nodemailer, you should require the nodemailer package in your Node.js programme.
const nodemailer = require('nodemailer');
Features available in nodemailer
To configure nodemailer, use the 'createTransport' function inside the nodemailer variable.
const transporter = nodemailer.createTransport({ mailOptions });
The mailOptions object (which defines the connection (detailed below)) contains multiple parameters used to create a transport.
Creating a SMTP transport
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 465,
secure: true,
auth: {
user: process.env.SMTP_USERNAME,
pass: process.env.SMTP_PASSWORD
}
});
- host("string") - default("localhost"): Hostname or IP address of the SMTP server.
- port("number") - default("587" ("465" if secure: true)): Port to connect to.
- secure("boolean") - default("false"): If "true", the connection will use TLS immediately (recommended for port "465").
- service("string"): Connection preset for a well‑known email service, for example "gmail". Overrides host, port, and secure if set. See the well‑known services list.
- auth("object"): Authentication data (see Authentication).
- authMethod("string") - Default("PLAIN"): Preferred authentication method.
Sending email using nodemailer
const info = await transporter.sendMail({
from,
to,
subject,
text,
html,
attachments
});
- from("string") - default("default email"): From email address.
- to("string"): To email address.
- subject("string"): Subject of the email.
- text("string"): Plane text body of the email.
- html("string"): Html body of the email.
- attachments("array"): Attachements of the email.