Nodemailer Library: Sending Email in JavaScript (Node.js)
Nodemailer is the most popular module for sending emails from Node.js applications. It provides a simple yet powerful API for working with various email services (SMTP, Gmail, Outlook, SendGrid, Amazon SES, etc.). The library supports HTML templates, attachments, data streams, and encryption (SSL/TLS).
Why is Nodemailer needed?
In modern web development, sending email is a basic functionality: registration letters, password reset, notifications, newsletters. Nodemailer solves the following tasks:
- Universal work with any SMTP server.
- Support for HTML and text messages.
- Attached files (images, PDFs, archives).
- Streaming large data.
- Integration with popular services (Gmail, Yandex, Mail.ru).
Installation
Install the module via npm:
npm install nodemailerFor TypeScript additionally:
npm install @types/nodemailerMain Functions
- createTransport() — creating a transport to connect to the mail server.
- sendMail() — sending an email with settings (from, to, subject, body, attachments).
- verify() — verifying the connection to the server.
- use() — connecting plugins (e.g., for templating).
Code Example in Node.js
const nodemailer = require('nodemailer');
// Setting up transport (example for Gmail with App Password)const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your-email@gmail.com', pass: 'your-app-password' // Not a regular password, but an app password }});
// Function to send emailasync function sendEmail() { try { const info = await transporter.sendMail({ from: '"Your Name" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Hello from Node.js!', html: '<h1>Test Email</h1><p>Sent via Nodemailer.</p>' }); console.log('Message sent: %s', info.messageId); } catch (error) { console.error('Error sending:', error); }}
sendEmail();When to use Nodemailer?
- Registration and Authorization — sending email confirmation letters.
- Notifications — alerts about user actions (order, comment).
- Newsletters — mass sending (but for large volumes it's better to use SendGrid/Mailgun).
- Debugging — sending emails in a local environment (via Ethereal or Mailtrap).
Important: For production, use real SMTP servers (SendGrid, Amazon SES, Mailgun) or configure your own mail server. Gmail has limits (500 emails/day) and requires an app password.
Nodemailer is the de facto standard for sending email in Node.js. It is simple, reliable, and has a large community.
Also in library
Guzzle for PHP: Complete Guide with Examples
GraphQL Library in C++: Implementing API with graphql-cpp
Email Sending in JavaScript (Node.js) — Libraries and Code Examples
Working with Dates in TypeScript: Popular Libraries and Examples