UNPKG

@upyo/smtp

Version:

SMTP transport for Upyo email library

298 lines (296 loc) 8.27 kB
import { Message, Receipt, Transport, TransportOptions } from "@upyo/core"; //#region src/config.d.ts /** * Configuration interface for SMTP transport connection settings. * * This interface defines all available options for configuring an SMTP * connection including server details, authentication, security, and * connection pooling settings. * * @example * ```typescript * const config: SmtpConfig = { * host: 'smtp.gmail.com', * port: 465, * secure: true, // Use TLS from start * auth: { * user: 'user@gmail.com', * pass: 'app-password' * }, * connectionTimeout: 30000, * poolSize: 10 * }; * ``` */ interface SmtpConfig { /** * The SMTP server hostname or IP address. */ readonly host: string; /** * The SMTP server port number. * @default 587 */ readonly port?: number; /** * Whether to use secure connection (TLS/SSL). * @default true */ readonly secure?: boolean; /** * Authentication configuration for the SMTP server. */ readonly auth?: SmtpAuth; /** * TLS configuration options. */ readonly tls?: SmtpTlsOptions; /** * Connection timeout in milliseconds. * @default 60000 */ readonly connectionTimeout?: number; /** * Socket timeout in milliseconds. * @default 60000 */ readonly socketTimeout?: number; /** * The name to use for the local hostname in the HELO/EHLO command. */ readonly localName?: string; /** * Pool connections to reuse them. * @default true */ readonly pool?: boolean; /** * Maximum number of connections in the pool. * @default 5 */ readonly poolSize?: number; } /** * Authentication configuration for SMTP connections. * * Defines the credentials and authentication method to use when * connecting to an SMTP server that requires authentication. * * @example * ```typescript * const auth: SmtpAuth = { * user: 'username@domain.com', * pass: 'password', * method: 'plain' // or 'login', 'cram-md5' * }; * ``` */ interface SmtpAuth { /** * Username for authentication. */ readonly user: string; /** * Password for authentication. */ readonly pass: string; /** * Authentication method. * @default "plain" */ readonly method?: "plain" | "login" | "cram-md5"; } /** * TLS/SSL configuration options for secure SMTP connections. * * These options control the behavior of TLS encryption when connecting * to SMTP servers, including certificate validation and client authentication. * * @example * ```typescript * const tlsOptions: SmtpTlsOptions = { * rejectUnauthorized: true, * minVersion: 'TLSv1.2', * ca: [fs.readFileSync('ca-cert.pem', 'utf8')] * }; * ``` */ interface SmtpTlsOptions { /** * Whether to reject unauthorized certificates. * @default true */ readonly rejectUnauthorized?: boolean; /** * List of trusted certificates. */ readonly ca?: string[]; /** * Private key for client certificate authentication. */ readonly key?: string; /** * Certificate for client certificate authentication. */ readonly cert?: string; /** * Minimum TLS version to accept. * @default "TLSv1.2" */ readonly minVersion?: "TLSv1" | "TLSv1.1" | "TLSv1.2" | "TLSv1.3"; /** * Maximum TLS version to accept. * @default "TLSv1.3" */ readonly maxVersion?: "TLSv1" | "TLSv1.1" | "TLSv1.2" | "TLSv1.3"; } /** * Resolved SMTP configuration with all optional fields filled with default values. * * This type represents the final configuration after applying defaults, * used internally by the SMTP transport implementation. */ //#endregion //#region src/smtp-transport.d.ts /** * SMTP transport implementation for sending emails via SMTP protocol. * * This transport provides efficient email delivery with connection pooling, * support for authentication, TLS/SSL encryption, and batch sending capabilities. * * @example * ```typescript * import { SmtpTransport } from '@upyo/smtp'; * * // Automatic resource cleanup with using statement * await using transport = new SmtpTransport({ * host: 'smtp.gmail.com', * port: 465, * secure: true, // Use TLS from start * auth: { * user: 'user@gmail.com', * pass: 'app-password' * } * }); * * const receipt = await transport.send(message); * // Connections are automatically closed here * * // Or manual management * const transport2 = new SmtpTransport(config); * try { * await transport2.send(message); * } finally { * await transport2.closeAllConnections(); * } * ``` */ declare class SmtpTransport implements Transport, AsyncDisposable { /** * The SMTP configuration used by this transport. */ config: SmtpConfig; /** * The maximum number of connections in the pool. */ poolSize: number; private connectionPool; /** * Creates a new SMTP transport instance. * * @param config SMTP configuration including server details, authentication, * and options. */ constructor(config: SmtpConfig); /** * Sends a single email message via SMTP. * * This method converts the message to SMTP format, establishes a connection * to the SMTP server, sends the message, and returns a receipt with the result. * * @example * ```typescript * const receipt = await transport.send({ * sender: { address: 'from@example.com' }, * recipients: [{ address: 'to@example.com' }], * subject: 'Hello', * content: { text: 'Hello World!' } * }); * * if (receipt.successful) { * console.log('Message sent with ID:', receipt.messageId); * } * ``` * * @param message The email message to send. * @param options Optional transport options including `AbortSignal` for * cancellation. * @returns A promise that resolves to a receipt indicating success or * failure. */ send(message: Message, options?: TransportOptions): Promise<Receipt>; /** * Sends multiple email messages efficiently using a single SMTP connection. * * This method is optimized for bulk email sending by reusing a single SMTP * connection for all messages, which significantly improves performance * compared to sending each message individually. * * @example * ```typescript * const messages = [ * { subject: 'Message 1', recipients: [{ address: 'user1@example.com' }], ... }, * { subject: 'Message 2', recipients: [{ address: 'user2@example.com' }], ... } * ]; * * for await (const receipt of transport.sendMany(messages)) { * if (receipt.successful) { * console.log('Sent:', receipt.messageId); * } else { * console.error('Failed:', receipt.errorMessages); * } * } * ``` * * @param messages An iterable or async iterable of messages to send. * @param options Optional transport options including `AbortSignal` for * cancellation. * @returns An async iterable of receipts, one for each message. */ sendMany(messages: Iterable<Message> | AsyncIterable<Message>, options?: TransportOptions): AsyncIterable<Receipt>; private getConnection; private connectAndSetup; private returnConnection; private discardConnection; /** * Closes all active SMTP connections in the connection pool. * * This method should be called when shutting down the application * to ensure all connections are properly closed and resources are freed. * * @example * ```typescript * // At application shutdown * await transport.closeAllConnections(); * ``` */ closeAllConnections(): Promise<void>; /** * Implements AsyncDisposable interface for automatic resource cleanup. * * This method is called automatically when using the `using` keyword, * ensuring that all SMTP connections are properly closed when the * transport goes out of scope. * * @example * ```typescript * // Automatic cleanup with using statement * await using transport = new SmtpTransport(config); * await transport.send(message); * // Connections are automatically closed here * ``` */ [Symbol.asyncDispose](): Promise<void>; } //#endregion export { SmtpAuth, SmtpConfig, SmtpTlsOptions, SmtpTransport };