CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nodemailer

Easy as cake e-mail sending from your Node.js applications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Nodemailer

Nodemailer is a comprehensive Node.js email delivery library that simplifies sending emails from Node.js applications through its easy-to-use API. It provides extensive SMTP transport support with authentication mechanisms including OAuth2, supports various email formats (plain text, HTML, attachments), offers built-in security features like DKIM signing and TLS encryption, includes template engine integration capabilities, and provides debugging and logging functionality.

Package Information

  • Package Name: nodemailer
  • Package Type: npm
  • Language: JavaScript/Node.js
  • Installation: npm install nodemailer

Core Imports

const nodemailer = require('nodemailer');

ES Modules:

import nodemailer from 'nodemailer';
// or
import { createTransport, createTestAccount, getTestMessageUrl } from 'nodemailer';

Basic Usage

const nodemailer = require('nodemailer');

// Create transporter object using SMTP transport
let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'your.email@gmail.com',
        pass: 'your-password'
    }
});

// Define email options
let mailOptions = {
    from: '"Sender Name" <sender@example.com>',
    to: 'recipient@example.com',
    subject: 'Hello ✔',
    text: 'Hello world?',
    html: '<b>Hello world?</b>'
};

// Send email
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
});

Architecture

Nodemailer is built around several key components:

  • Transport Layer: Pluggable transport system supporting SMTP, SMTP Pool, SES, Sendmail, Stream, and JSON transports
  • Mailer Class: Core email sending interface with plugin support and event handling
  • Message Composition: Advanced MIME message building with support for attachments, embedded images, and alternative content
  • Authentication: Multiple authentication methods including basic auth, OAuth2, and custom SASL mechanisms
  • Security Features: Built-in DKIM signing, TLS encryption, and proxy support
  • Testing Integration: Ethereal Email service integration for development and testing

Capabilities

Transport Creation

Core functionality for creating email transport instances with various backends and configuration options.

/**
 * Creates a transport object for sending emails
 * @param {Object|string} transporter - Transport configuration or connection URL
 * @param {Object} [defaults] - Default message options
 * @returns {Mailer} Mailer instance
 */
function createTransport(transporter, defaults);

Transport Configuration

Email Sending

Main email sending functionality with support for various message formats, attachments, and delivery options.

/**
 * Sends an email message
 * @param {Object} mailOptions - Email message configuration
 * @param {Function} [callback] - Optional callback function
 * @returns {Promise} Promise if no callback provided
 */
sendMail(mailOptions, callback);

interface MailOptions {
    from?: string | Address;
    to: string | string[] | Address | Address[];
    cc?: string | string[] | Address | Address[];
    bcc?: string | string[] | Address | Address[];
    subject?: string;
    text?: string | Buffer | NodeJS.ReadableStream;
    html?: string | Buffer | NodeJS.ReadableStream;
    attachments?: Attachment[];
    headers?: Object;
    priority?: 'high' | 'normal' | 'low';
    date?: Date | string;
    encoding?: string;
    envelope?: Object;
    messageId?: string;
    replyTo?: string | string[] | Address | Address[];
    inReplyTo?: string | string[];
    references?: string | string[];
    watchHtml?: string | Buffer | NodeJS.ReadableStream;
    amp?: string | Buffer | NodeJS.ReadableStream;
    icalEvent?: Object;
    alternatives?: Alternative[];
    list?: ListHeaders;
    dsn?: Object;
    sender?: string | Address;
    raw?: string | Buffer;
}

interface Attachment {
    filename?: string;
    content?: string | Buffer | NodeJS.ReadableStream;
    path?: string;
    href?: string;
    contentType?: string;
    contentDisposition?: string;
    cid?: string;
    encoding?: string;
    headers?: Object;
    raw?: string | Buffer;
}

interface ListHeaders {
    help?: string;
    unsubscribe?: string | string[];
    subscribe?: string | string[];
    post?: string | string[];
    owner?: string | string[];
    archive?: string | string[];
    id?: { url: string; comment?: string };
}

interface Address {
    name?: string;
    address: string;
}

interface Alternative {
    contentType: string;
    content: string | Buffer | NodeJS.ReadableStream;
    encoding?: string;
    raw?: string | Buffer;
}

Email Sending

Test Account Management

Development and testing utilities for creating temporary email accounts and viewing sent messages.

/**
 * Creates a test account on Ethereal Email service
 * @param {string} [apiUrl] - Optional API endpoint URL
 * @param {Function} [callback] - Optional callback function
 * @returns {Promise} Promise if no callback provided
 */
function createTestAccount(apiUrl, callback);

/**
 * Generates URL to view sent test message on Ethereal
 * @param {Object} info - Send result info object
 * @returns {string|false} Message URL or false if not available
 */
function getTestMessageUrl(info);

Testing Support

Plugin System

Extensible plugin architecture for customizing email processing and adding functionality.

/**
 * Adds a plugin to the mail processing pipeline
 * @param {string} step - Processing step ('compile' or 'stream')
 * @param {Function} plugin - Plugin function
 * @returns {Mailer} this (chainable)
 */
use(step, plugin);

Plugin Development

Authentication Methods

Comprehensive authentication support including basic credentials, OAuth2, and custom SASL mechanisms.

interface BasicAuth {
    user: string;
    pass: string;
}

interface OAuth2Auth {
    type: 'OAuth2';
    user: string;
    clientId: string;
    clientSecret: string;
    refreshToken: string;
    accessToken?: string;
    expires?: Date;
    accessUrl?: string;
}

interface CustomAuth {
    type: string;
    user: string;
    method?: string;
    options?: Object;
}

Authentication

Connection Management

Transport connection lifecycle management including verification, pooling, and cleanup.

/**
 * Verifies transport configuration
 * @param {Function} [callback] - Optional callback function
 * @returns {Promise} Promise if no callback provided
 */
verify(callback);

/**
 * Checks if transport is idle (for pooled transports)
 * @returns {boolean} True if idle
 */
isIdle();

/**
 * Closes the transport connection
 * @returns {void}
 */
close();

/**
 * Sets a metadata value for the Mailer instance
 * @param {string} key - Metadata key
 * @param {*} value - Metadata value
 * @returns {Mailer} this (chainable)
 */
set(key, value);

/**
 * Gets a metadata value from the Mailer instance
 * @param {string} key - Metadata key
 * @returns {*} Metadata value or undefined
 */
get(key);

Connection Management

Types

/**
 * Main Mailer class extending EventEmitter
 */
class Mailer extends EventEmitter {
    constructor(transporter, options, defaults);
    
    // Core methods
    sendMail(mailOptions, callback);
    use(step, plugin);
    verify(callback);
    isIdle();
    close();
    set(key, value);
    get(key);
    
    // Events emitted:
    // - 'idle': Emitted when transport becomes idle (pooled transports)
    // - 'error': Emitted when transport encounters an error
    // - 'clear': Emitted when all connections are terminated
}

/**
 * Transport configuration options
 */
interface TransportOptions {
    // SMTP options
    host?: string;
    port?: number;
    secure?: boolean;
    auth?: BasicAuth | OAuth2Auth | CustomAuth;
    tls?: TLSOptions;
    service?: string; // Well-known service names like 'Gmail', 'Yahoo', etc.
    
    // Pool options
    pool?: boolean;
    maxConnections?: number;
    maxMessages?: number;
    rateDelta?: number;
    rateLimit?: number;
    
    // General options
    name?: string;
    localAddress?: string;
    logger?: boolean | Object;
    debug?: boolean;
    connectionTimeout?: number;
    greetingTimeout?: number;
    socketTimeout?: number;
    proxy?: string;
    
    // DKIM options
    dkim?: DKIMOptions;
    
    // Alternative transports
    sendmail?: boolean;
    path?: string;
    args?: string[];
    streamTransport?: boolean;
    jsonTransport?: boolean;
    SES?: SESOptions;
}

interface TLSOptions {
    rejectUnauthorized?: boolean;
    ciphers?: string;
    minVersion?: string;
    maxVersion?: string;
    ca?: string | Buffer | Array<string | Buffer>;
    cert?: string | Buffer;
    key?: string | Buffer;
    passphrase?: string;
}

interface DKIMOptions {
    domainName: string;
    keySelector: string;
    privateKey: string | Buffer;
    cacheDir?: string;
    cacheTreshold?: number;
    hashAlgo?: string;
    skipFields?: string;
}

interface SESOptions {
    sesClient?: any; // AWS SES v2 client instance
}

/**
 * Send result information
 */
interface SentMessageInfo {
    messageId: string;
    envelope: {
        from: string;
        to: string[];
    };
    accepted: string[];
    rejected: string[];
    pending: string[];
    response: string;
}

docs

authentication.md

connection.md

index.md

plugins.md

sending.md

testing.md

transports.md

tile.json