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
- Provides a straightforward API to send emails with minimal code.
- Supports various methods for sending emails, including SMTP servers (e.g., Gmail, Zoho), Sendmail, and Amazon SES (Simple Email Service).
- The option to send email in multiple foramts such as Plain text, HTML emails with plain-text fallbacks, and Emails with attachments and embedded images.
- Includes TLS/STARTTLS encryption and support for DKIM signing and OAuth2 authentication.
- A zero-dependency module, meaning it does not rely on other runtime packages for its core functionality.
Configuration of 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.
To know more details about it, use this link to refer to the detailed documentation.
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.
If you have any other doubts, please refer to official documentation.