Nodemailer: sending email on JavaScript (Node.js)
Nodemailer is the most popular module for sending emails from Node.js applications. It provides a simple and flexible API for working with SMTP servers, and also supports HTML templates, attachments, streaming, and multiple transports (SMTP, Sendmail, Amazon SES, and others).
Why is Nodemailer needed?
Web applications often require sending emails: registration confirmations, password resets, notifications, newsletters. Nodemailer allows you to do this without unnecessary dependencies, with support for OAuth2, SSL/TLS, and encodings. It works asynchronously and does not block the Event Loop.
Installation
Install the module via npm:
npm install nodemailerWorking with Gmail or Yandex.Mail may require additional configuration (app password or OAuth2).
Main features
- Sending via SMTP, Sendmail, AWS SES, Mailgun, SendGrid
- Support for HTML and text emails
- Attachments (files, images, Buffer, Stream)
- OAuth2 authentication (Gmail, Outlook)
- Connection pool for mass mailing
- Templating (Handlebars, EJS integration)
Code example on JavaScript (Node.js)
A simple example of sending an email via Gmail SMTP:
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password'
}
});
const mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient@example.com',
subject: 'Hello from Node.js',
html: '<h1>Test email</h1><p>Sent via Nodemailer</p>'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log('Error:', error);
} else {
console.log('Email sent:', info.response);
}
});When to use
Nodemailer is suitable for any Node.js projects that need email sending: from simple scripts to enterprise applications. It is stable, well-documented, and supported by thousands of developers. If you need mass mailing (newsletter), it is better to use specialized services (SendGrid, Mailchimp) via their API, but for transactional email, Nodemailer is the ideal choice.