A modern, TypeScript-first email library for Node.js with full SMTP implementation from scratch
npm install @oxog/mailer
Built from the ground up with modern standards and best practices
No runtime dependencies. SMTP, MIME and authentication are implemented with Node.js built-in modules only (net, tls, crypto).
Written in TypeScript and ships its own declarations for both import and require().
Promise-based API for async/await. Concurrent send() calls are queued safely on the connection.
Optional connection pool (pool, maxConnections, maxMessages) and a messages-per-second rateLimit.
Implicit TLS and STARTTLS with certificate verification on by default; requireTLS refuses plain-text sessions. PLAIN, LOGIN, CRAM-MD5 and XOAUTH2. CR/LF in headers is rejected before sending.
Small plugin system on top of beforeSend / afterSend events.
Install, point it at your SMTP server, send
npm install @oxog/mailer
Works with import { Mailer } from '@oxog/mailer' and const { Mailer } = require('@oxog/mailer'). Tested on Node.js 18 to 24.
import { Mailer } from '@oxog/mailer'; const mailer = new Mailer({ host: 'smtp.gmail.com', port: 587, secure: false, // STARTTLS on port 587 requireTLS: true, // fail instead of sending in plain text auth: { user: 'your-email@gmail.com', pass: 'your-app-password', }, }); async function sendEmail() { const result = await mailer.send({ from: 'sender@example.com', to: 'recipient@example.com', subject: 'Hello from @oxog/mailer!', text: 'This is a test email.', html: '<h1>Hello!</h1><p>This is a test email.</p>', }); console.log('Email sent:', result.messageId); console.log(result.accepted, result.response); // e.g. '250 2.0.0 Ok: queued as ...' await mailer.close(); } sendEmail().catch(console.error);
Quick setup for popular email providers (port 587 with STARTTLS and requireTLS: true). Also available: createYahooClient and createOutlookOAuth2Client.
const gmailMailer = Mailer.createGmailClient( 'user@gmail.com', 'app-password' );
const outlookMailer = Mailer.createOutlookClient( 'user@outlook.com', 'password' );
const gmailOAuth = Mailer.createGmailOAuth2Client( 'user@gmail.com', 'access-token' );
Real-world usage examples
await mailer.send({ from: 'sender@example.com', to: 'recipient@example.com', subject: 'Report Attachment', html: ` <h2>Monthly Report</h2> <p>Please find the report attached.</p> `, attachments: [ { filename: 'report.pdf', path: './reports/monthly.pdf', contentType: 'application/pdf' } ] });
await mailer.send({ from: 'sender@example.com', to: [ 'team@example.com', { name: 'John Doe', address: 'john@example.com' } ], cc: 'manager@example.com', bcc: 'archive@example.com', subject: 'Team Update', text: 'Weekly team update...' });
import type { Mailer, Plugin, Message, SendResult } from '@oxog/mailer'; const loggerPlugin: Plugin = { name: 'logger', install(mailer: Mailer) { mailer.on('beforeSend', (message: Message) => { console.log('Sending:', message.subject); }); mailer.on('afterSend', (result: SendResult) => { console.log('Sent:', result.messageId); }); } }; mailer.use(loggerPlugin);
import { MailerError, ErrorCodes } from '@oxog/mailer'; try { await mailer.send(message); } catch (error) { if (error instanceof MailerError) { console.error('Error:', error.code, error.message); console.error('SMTP reply:', error.statusCode, error.response); console.error('Solution:', error.solution); if (error.code === ErrorCodes.AUTH_FAILED) { // 'EAUTH': check credentials / app password } } }
Options, message fields and methods. See the README for the full reference and error codes.
host: string
SMTP server hostname (required)
port?: number
SMTP server port (default: 465 when secure is true, otherwise 587)
secure?: boolean
Implicit TLS from the first byte, usually port 465 (default: false; STARTTLS is used when the server offers it)
auth?: { type?, user, pass?, accessToken? }
Credentials; type is 'plain' | 'login' | 'cram-md5' | 'xoauth2' (chosen from the server's offer when omitted)
rateLimit?: number
Rate limit in messages per second (default: 0, no limit)
requireTLS?: boolean
Fail with ETLS instead of authenticating or sending in plain text when the server does not offer STARTTLS (default: false; the provider factory methods set it)
tls?: { rejectUnauthorized?, minVersion?, ciphers?, ca?, servername? }
TLS settings. Certificates are verified by default; use ca to trust a private CA instead of disabling verification
pool?: boolean | { max?, idle?, acquire? }
Use several connections in parallel; maxConnections (default: 5) and maxMessages per connection (default: 100) apply
connectionTimeout? / greetingTimeout? / socketTimeout?
Timeouts in ms (defaults: 10000 / 5000 / 60000)
name?: string
Client hostname sent with EHLO/HELO (default: 'localhost')
logger?: boolean | Logger, debug?: boolean
Logging; credentials are masked in the debug log
from: string | Address
Sender address (required)
to? / cc? / bcc?: string | Address | Array<string | Address>
Recipients (at least one of to, cc, bcc is required)
subject: string
Email subject (required)
text?: string
Plain text body
html?: string
HTML body (text or html is required)
attachments?: Attachment[]
Each with filename, and content (string, Buffer or readable stream) or path; optional contentType, cid for inline images, encoding
headers? / priority? / messageId? / inReplyTo? / references? / date?
Extra headers and threading fields. CR/LF in any header value is rejected with ECONFIG; non-ASCII values are RFC 2047 encoded
Send an email message. Rejects with a MailerError on failure
Returns: Promise<SendResult> (messageId, accepted, rejected, response, envelope)
Connect (and authenticate) to check the settings. Resolves false instead of throwing
Returns: Promise<boolean>
Uninstall plugins and close the connection(s)
Returns: Promise<void>
Install a plugin (unuse(name) removes it, getInstalledPlugins() lists them)
Returns: this
beforeSend (message), afterSend (result), close, and error. error is only emitted when a listener is registered; failures always reject the send() promise