Email Sending in JavaScript (Node.js): A Complete Guide
In modern web development, the ability to programmatically send emails is a critical feature for any serious application. Whether it's registration confirmation, password reset, notifications, or marketing campaigns, Node.js offers several powerful solutions for integrating email functionality. In this article, we will thoroughly examine three of the most popular approaches: the built-in nodemailer library, the cloud service SendGrid, and the flexible Mailgun API.
Why Do You Need a Separate Library for Sending Email?
Node.js does not have built-in tools for working with the SMTP protocol or REST APIs of email services. Therefore, developers use specialized libraries that handle:
- Forming correct MIME messages (including HTML, attachments, inline images);
- Managing queues and retry attempts on network errors;
- Secure storage and transmission of credentials;
- Support for popular email providers (Gmail, Yandex, Mail.ru, corporate servers).
1. Nodemailer — Universal SMTP Client
Nodemailer is the de facto standard for sending email in Node.js. It supports both classic SMTP and integration with OAuth2. The library works without additional dependencies and allows sending emails through any SMTP server.
Installation
npm install nodemailerBasic Example of Sending via Gmail SMTP
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure: false, // true for 465, false for others auth: { user: 'your-email@gmail.com', pass: 'your-app-password' // Use an app password, not your main one! }});
const mailOptions = { from: '"Sender Name" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Hello from Node.js', text: 'This is a simple text email.', html: '<b>This is bold text in HTML</b>'};
transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log('Error:', error); } console.log('Email sent: %s', info.messageId);});Working with Attachments
mailOptions.attachments = [ { // file on disk filename: 'document.pdf', path: '/path/to/document.pdf' }, { // content as a string filename: 'notes.txt', content: 'Text file created on the fly' }];2. SendGrid — Cloud Service for Transactional Emails
SendGrid (now part of Twilio) provides a powerful REST API and guarantees high deliverability. The @sendgrid/mail library simplifies integration. It is suitable for projects where analytics of opens, clicks, and unsubscribes are important.
Installation
npm install @sendgrid/mailExample of Sending
const sgMail = require('@sendgrid/mail');sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = { to: 'recipient@example.com', from: 'sender@yourdomain.com', // Domain must be verified in SendGrid subject: 'Service Notification', text: 'Text version of the email', html: '<h1>Hello!</h1><p>This email was sent via SendGrid.</p>',};
sgMail.send(msg) .then(() => console.log('Email sent successfully')) .catch((error) => console.error(error.toString()));Sending with Dynamic Templates
const msg = { to: 'user@example.com', from: 'test@example.com', templateId: 'd-xxxxxxxxxxxxxxxxxxxx', // Template ID from SendGrid dynamicTemplateData: {