Sending Email in JavaScript (Node.js): nodemailer, sendgrid, mailgun
Sending email is one of the key functions of modern web applications: user registration, password resets, notifications, and marketing campaigns. In the Node.js ecosystem, there are several proven solutions that allow you to integrate email functionality in minutes. In this article, we will thoroughly examine three popular tools: nodemailer, sendgrid, and mailgun. You will learn how to configure SMTP, send emails with attachments and HTML templates, and which metrics to track.
1. Nodemailer — Universal SMTP Client
Nodemailer is the most popular library for sending email in Node.js. It supports SMTP, SES, Sendmail, and many transports. Key advantages:
- Simple setup via an SMTP account (Gmail, Yandex, Mail.ru).
- Support for attachments, inline images, HTML templates.
- Working with queues and connection pools.
- Asynchronous sending via
async/await.
Installation and Basic Sending
npm install nodemailerconst nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure: false, // true for port 465 auth: { user: 'your-email@gmail.com', pass: 'your-password' // or app-password }});
const mailOptions = { from: '"Sender" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Hello from Node.js!', text: 'This is a test email.', html: '<h1>Hello!</h1><p>This is the HTML version.</p>'};
const sendMail = async () => { const info = await transporter.sendMail(mailOptions); console.log('Email sent:', info.messageId);};
sendMail().catch(console.error);Sending with Attachments
const mailOptions = { // ...basic fields attachments: [ { filename: 'document.pdf', path: '/path/to/document.pdf' }, { filename: 'image.png', content: fs.createReadStream('/path/to/image.png') } ]};Important: For Gmail, use an app password or OAuth2.
2. SendGrid — Cloud Service for Transactional Emails
SendGrid (part of Twilio) provides a powerful API for sending email with high deliverability. Suitable for startups and large projects. Key features:
- API with access keys (no SMTP).
- Dynamic templates (Handlebars).
- Analytics: opens, clicks, unsubscribes.
- Free tier up to 100 emails/day.
Installation and Sending
npm install @sendgrid/mailconst sgMail = require('@sendgrid/mail');sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = { to: 'recipient@example.com', from: 'sender@example.com', subject: 'Transactional Email', text: 'Email text', html: '<strong>HTML content</strong>', attachments: [ { content: 'base64encodedcontent', filename: 'invoice.pdf', type: 'application/pdf', disposition: 'attachment' } ]};
sgMail.send(msg) .then(() => console.log('Email sent')) .catch(console.error);Using Dynamic Templates
const msg = { to: 'user@example.com', from: 'noreply@mysite.com', templateId: 'd-xxxxxxxxxxxxxxxx', dynamicTemplateData: { username: 'Ivan', orderLink: 'https://mysite.com/order/123' }};