Email Sending in TypeScript: A Complete Guide
TypeScript is a strictly typed superset of JavaScript that is actively used in modern web applications. Sending email is one of the key tasks for backend, notifications, and marketing. In this article, we will thoroughly examine several libraries for sending email in TypeScript, including setup, sending simple and HTML emails, as well as working with attachments.
Why TypeScript for Sending Email?
TypeScript adds typing, which reduces the number of errors at the development stage. When sending email, this is especially important: correct types for the SMTP host, port, credentials, and email options help avoid runtime errors. Additionally, TypeScript supports modern async/await constructs, making the code cleaner and more understandable.
Main Libraries for Sending Email in TypeScript
- nodemailer — the most popular library for Node.js, fully compatible with TypeScript. Supports SMTP, Sendmail, attachments, HTML templates.
- @sendgrid/mail — the official SendGrid client for Node.js with TypeScript types. Uses the SendGrid API, does not require SMTP.
- aws-sdk (SES) — Amazon Simple Email Service. A powerful solution for mass mailings, integration with AWS.
- emailjs — a lightweight library with TypeScript support, but less popular.
Installing and Configuring nodemailer with TypeScript
Install the packages via npm:
npm install nodemailernpm install @types/nodemailer --save-devA basic example of sending email via SMTP (Gmail, Yandex, Mail.ru, etc.):
import nodemailer from 'nodemailer';
interface EmailOptions { to: string; subject: string; text?: string; html?: string;}
async function sendEmail(options: EmailOptions): Promise<void> { 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: '"Your Name" <your-email@gmail.com>', to: options.to, subject: options.subject, text: options.text, html: options.html, };
const info = await transporter.sendMail(mailOptions); console.log('Email sent:', info.messageId);}
// UsagesendEmail({ to: 'user@example.com', subject: 'Hello from TypeScript!', html: '<h1>Test</h1><p>This is an HTML email.</p>',});Important: For Gmail, enable "Access to less secure apps" or use an App Password. For production, it is better to use OAuth2.
Sending Email via SendGrid in TypeScript
SendGrid provides a ready-made API that does not require SMTP. Installation:
npm install @sendgrid/mailExample of sending:
import sgMail from '@sendgrid/mail';
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');
interface SendGridMessage { to: string; from: string; subject: string; html: string;}
async function sendWithSendGrid(message: SendGridMessage): Promise<void> { try { await sgMail.send(message); console.log('Email sent via SendGrid'); } catch (error) { console.error('Error sending:', error); }}
sendWithSendGrid({ to: 'user@example.com', from: 'sender@yourdomain.com', subject: 'Test SendGrid + TypeScript', html: '<p>This message was sent via the SendGrid API.</p>',});Sending Email with Attachments in TypeScript
nodemailer supports attachments of any type. Example with a PDF file:
import nodemailer from 'nodemailer';import path from 'path';
async function sendWithAttachment() Also in library
Object Serialization in Swift (iOS/macOS): Codable, JSON and PropertyList
Rate Limiting in Java: Libraries and Tools for Request Control (Bucket4j, Resilience4j)
OAuth client for Go (Golang): Connecting to OAuth 2.0 providers
HTML Parsing in C# (.NET): HtmlAgilityPack and AngleSharp Libraries