Nodemailer — sending email in TypeScript

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Nodemailer and why is it needed?

Nodemailer is the most popular module for sending emails in the Node.js environment. Written in JavaScript, it works perfectly with TypeScript thanks to built-in types (DefinitelyTyped). The library allows sending emails via SMTP, Sendmail, Amazon SES, and other transports. In TypeScript projects, Nodemailer provides strict typing for all options, which reduces the number of errors at the compilation stage.

Installation

To install, run the command:

npm install nodemailer @types/nodemailer

The @types/nodemailer package adds type declarations required for TypeScript.

Main Features

  • Sending emails via SMTP — support for Gmail, Yandex, Mail.ru, SendGrid, and any other SMTP servers.
  • Attachments — ability to attach files, images, PDFs.
  • HTML templates — sending emails with formatted HTML content.
  • SSL/TLS support — secure data transmission.
  • Connection pool — optimization for mass mailing.

Code Example in TypeScript

Below is a minimal example of sending an email via Gmail SMTP using TypeScript:

import nodemailer from 'nodemailer';

interface MailOptions { from: string; to: string; subject: string; text?: string; html?: string;}

async function sendEmail(options: MailOptions): Promise<void> { const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your@gmail.com', pass: 'your-app-password', }, });

const info = await transporter.sendMail(options); console.log('Email sent:', info.messageId);}

// UsagesendEmail({ from: 'your@gmail.com', to: 'recipient@example.com', subject: 'Hello from TypeScript!', html: '<h1>Test email</h1><p>Sent using Nodemailer</p>',});

Important: For Gmail, you need to use an App Password, not your regular password.

When to use Nodemailer?

The library is suitable for:

  • Registration emails (email confirmation, password recovery).
  • Order notifications in online stores.
  • Newsletter and marketing email campaigns (using queues).
  • Automatic reports from the backend (logs, errors, statistics).

If you need email sending in a TypeScript project — Nodemailer remains the de facto standard thanks to its flexibility, reliability, and huge community.

Recommendations