### Simple Echo Server Setup Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt A basic example demonstrating how to set up a simple echo server using the SMTP server. This is useful for initial testing and understanding the server's core functionality. ```javascript import { SMTPServer } from 'smtp-server'; const server = new SMTPServer({ // Allow only anonymous connections disabledCommands: ['AUTH', 'STARTTLS'], onData: (stream, session, callback) => { console.log(`Receiving message from ${session.remoteAddress}`); stream.pipe(process.stdout); // Pipe message to stdout stream.on('end', () => callback(null, 'Message accepted')); } }); server.listen(25, () => { console.log('SMTP server listening on port 25'); }); ``` -------------------------------- ### Complete SMTP Server Configuration Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md A comprehensive example demonstrating the setup of an SMTP server with identity, security (TLS), limits, protocol options, logging, and essential event handlers. ```javascript const SMTPServer = require('smtp-server').SMTPServer; const fs = require('fs'); const server = new SMTPServer({ // Identity name: 'mail.example.com', banner: 'ACME Mail System', // Security secure: true, key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem'), // Limits maxClients: 100, socketTimeout: 300000, size: 50 * 1024 * 1024, // Protocol lmtp: false, authMethods: ['PLAIN', 'CRAM-MD5'], authOptional: false, disabledCommands: ['VRFY', 'EXPN'], hideENHANCEDSTATUSCODES: false, // Logging logger: true, // Handlers onAuth: (auth, session, cb) => { // Implementation cb(null, { user: 'id' }); }, onData: (stream, session, cb) => { stream.on('end', () => cb(null, 'Queued')); } }); ``` -------------------------------- ### STARTTLS Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Example of a client initiating STARTTLS, followed by a successful TLS handshake and re-advertisement of features via EHLO. ```smtp C: STARTTLS S: 220 Ready to start TLS (TLS handshake) C: EHLO mail.example.com S: 250 ... (features re-advertised) ``` -------------------------------- ### RSET Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Client-server interaction example for the RSET command, demonstrating the state reset. ```smtp C: RSET S: 250 OK ``` -------------------------------- ### XFORWARD Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Example of using the XFORWARD command to provide forwarding information. Requires `useXForward: true` in server options. ```smtp C: XFORWARD ADDR=192.0.2.1 NAME=source.example.com HELO=mail.source.com S: 200 OK ``` -------------------------------- ### NOOP Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Client-server interaction example for the NOOP command, showing the expected '250 OK' response. ```smtp C: NOOP S: 250 OK ``` -------------------------------- ### Create and Start an SMTP Server Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Instantiates a new SMTPServer with basic configuration and starts it listening on a specified port and interface. Requires the 'smtp-server' module. ```javascript const { SMTPServer } = require('smtp-server'); const server = new SMTPServer({ secure: false, logger: true, maxClients: 100 }); server.listen(25, '0.0.0.0'); ``` -------------------------------- ### XCLIENT Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Example of using the XCLIENT command to set client IP address, hostname, and HELO name for a connection, with the server responding '220 OK'. ```smtp C: XCLIENT ADDR=192.0.2.50 NAME=client.example.com PORT=54321 HELO=mail.client.com S: 220 OK ``` -------------------------------- ### Start SMTP Server with Callback Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Starts the SMTP server listening on a specific port and host, executing a callback function once the server is ready. This method is a passthrough to Node.js net.Server.listen(). ```javascript server.listen(25, 'localhost', () => { console.log('SMTP server listening on port 25'); }); ``` -------------------------------- ### SMTP Command Flows Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Illustrates a typical SMTP command flow. This example is conceptual and shows the sequence of commands exchanged between a client and the server. ```text Client: EHLO client.example.com Server: 250-smtp.example.com Server: 250-PIPELINING Server: 250-SIZE 10485760 Server: 250-VRFY Server: 250 HELP Client: MAIL FROM: Server: 250 2.1.0 Ok Client: RCPT TO: Server: 250 2.1.5 Ok Client: DATA Server: 354 End data with . Client: Subject: Test Message Client: Client: This is the body of the message. Client: . Server: 250 2.0.0 Ok: queued as 12345 Client: QUIT Server: 221 2.0.0 Bye ``` -------------------------------- ### Server with Authentication Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Example of setting up an SMTP server that requires authentication. It demonstrates how to implement custom authentication logic using the `onAuth` handler. ```javascript import { SMTPServer } from 'smtp-server'; const server = new SMTPServer({ authMethods: ['PLAIN', 'LOGIN', 'XOAUTH2'], onAuth: (auth, session, callback) => { // Use callback(null, { user: 'username' }) to accept authentication // Use callback(new Error('Invalid username or password')) to reject authentication if (auth.method === 'PLAIN' || auth.method === 'LOGIN') { if (auth.username === 'test' && auth.password === 'test') { return callback(null, { user: auth.username }); } } else if (auth.method === 'XOAUTH2') { // Implement XOAUTH2 validation here } callback(new Error('Invalid username or password')); }, onData: (stream, session, callback) => { console.log(`Receiving message from ${session.remoteAddress} by user ${session.user}`); stream.pipe(process.stdout); stream.on('end', () => callback(null, 'Message accepted')); } }); server.listen(25, () => { console.log('SMTP server listening on port 25 with authentication'); }); ``` -------------------------------- ### STARTTLS Configuration Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Configure the server to start unencrypted and upgrade to TLS using STARTTLS. Set 'secure' to false and 'needsUpgrade' to true. ```javascript new SMTPServer({ secure: false, needsUpgrade: true, key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') }) ``` -------------------------------- ### PLAIN Authentication Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md A client-server interaction example demonstrating PLAIN authentication. The server responds with a success code upon successful authentication. ```smtp C: AUTH PLAIN dGVzdHVzZXIAcGFzc3dvcmQ= S: 235 2.7.0 Authentication successful ``` -------------------------------- ### listen(...args) Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Starts listening on the specified port and interface, acting as a passthrough to Node.js's net.Server.listen(). ```APIDOC ## listen(port, [host], [callback]) ### Description Starts listening on the specified port and interface. This is a passthrough to the underlying Node.js net.Server.listen() method. ### Parameters #### Query Parameters - **port** (number) - Required - Port number to listen on - **host** (string) - Optional - Interface address - **callback** (function) - Optional - Called when server is listening ### Returns undefined ### Example ```javascript server.listen(25, 'localhost', () => { console.log('SMTP server listening on port 25'); }); ``` ``` -------------------------------- ### RCPT TO Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Demonstrates adding recipients to an email message using the RCPT TO command. ```smtp C: RCPT TO: S: 250 OK C: RCPT TO: NOTIFY=SUCCESS,FAILURE S: 250 OK ``` -------------------------------- ### DATA Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Shows the process of sending email content, including headers and body, using the DATA command. ```smtp C: DATA S: 354 Start mail input; end with . C: From: sender@example.com C: To: recipient@example.com C: Subject: Test C: C: This is a test message C: . S: 250 OK: message queued ``` -------------------------------- ### init() Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Initializes the connection, setting up listeners, checking limits, and starting the greeting sequence. This method is called automatically by SMTPServer and not typically by applications. ```APIDOC ## init() ### Description Initializes the connection, setting up listeners, checking limits, and starting the greeting sequence. This method is called automatically by SMTPServer and not typically by applications. ### Method Signature init() ### Returns undefined ### Details - Sets up socket event listeners - Checks maxClients limit - Begins the greeting sequence - Not typically called by applications ``` -------------------------------- ### IPv6 Address Normalization Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/errors.md Demonstrates the normalization of IPv6 addresses within square brackets for consistent representation. ```plaintext → normalized to [IPv6:2001:db8::1] ``` -------------------------------- ### AUTH LOGIN Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Demonstrates the obsolete LOGIN SASL mechanism for client authentication, involving username and password challenges. ```smtp AUTH LOGIN S: 334 VXNlcm5hbWU6 C: S: 334 UGFzc3dvcmQ6 C: S: 235 Authentication successful ``` -------------------------------- ### AUTH PLAIN Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Illustrates client authentication using the PLAIN SASL mechanism. ```smtp C: AUTH PLAIN dGVzdHVzZXIAdGVzdHVzZXIAdGVzdHBhc3M= S: 235 Authentication successful ``` -------------------------------- ### Quick Start: Basic SMTP Server Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md This snippet demonstrates how to create a basic SMTP server using the SMTPServer class. It includes authentication and data handling logic. The server listens on port 25. ```javascript const { SMTPServer } = require('smtp-server'); const server = new SMTPServer({ secure: false, auth: ['PLAIN', 'LOGIN'], onAuth: (auth, session, callback) => { if (auth.username === 'user' && auth.password === 'pass') { return callback(null, { user: 'id' }); } return callback(new Error('Invalid credentials')); }, onData: (stream, session, callback) => { stream.on('end', () => { if (stream.sizeExceeded) { const err = new Error('Message too large'); err.responseCode = 552; return callback(err); } callback(null, 'Message queued'); }); } }); server.listen(25); ``` -------------------------------- ### Event: 'listening' Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Emitted by the server when it starts listening for incoming connections. ```APIDOC ## Event: 'listening' ### Description Emitted by the server when it starts listening for incoming connections. ### Example ```javascript server.on('listening', () => { console.log('Server is listening'); }); ``` ``` -------------------------------- ### Punycode Domain Conversion Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/errors.md Illustrates the conversion of internationalized domain names from punycode. If conversion fails, the original domain is retained. ```plaintext → converted if possible, otherwise kept as-is ``` -------------------------------- ### QUIT Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Client-server interaction example for the QUIT command. The connection is closed after the server sends the '221 Bye' response. ```smtp C: QUIT S: 221 Bye (connection closes) ``` -------------------------------- ### SMTPServer Class Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Documentation for the main SMTPServer class, which handles the overall server setup and management. ```APIDOC ## SMTPServer Class ### Description This class is the main entry point for creating and managing an SMTP server instance. It handles server configuration, connection management, and listens for incoming connections. ### Public Methods - **new SMTPServer(options)**: Constructor for the SMTPServer class. Initializes the server with the provided options. - **listen()**: Starts the SMTP server and begins listening for incoming connections on the configured port and host. - **close()**: Stops the SMTP server and closes all active connections. ### Configuration Options Refer to `configuration.md` for a detailed list of all available server options. ``` -------------------------------- ### Session Management Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Illustrates the structure of the 'session' object available during a connection. This object holds connection-specific state like security status, authenticated user, and envelope details. ```javascript session = { id: string, // Unique connection ID secure: boolean, // TLS active user: any, // Set by onAuth handler envelope: { mailFrom: address, // Sender (set after MAIL) rcptTo: [], // Recipients (set after RCPT) bodyType: string, // '7bit' or '8bitmime' smtpUtf8: boolean, requireTLS: boolean, dsn: { ret, envid } } } ``` -------------------------------- ### MAIL FROM Command Example with Parameters Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Shows the MAIL FROM command used to initiate a new message, specifying the sender and message parameters like size and body type. This command requires a prior HELO or EHLO. ```smtp C: MAIL FROM: SIZE=1024 BODY=8BITMIME S: 250 OK ``` -------------------------------- ### Handle Server Listening Event Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Log a message when the SMTP server successfully starts listening for connections. ```javascript server.on('listening', () => { console.log('Server is listening'); }); ``` -------------------------------- ### AUTH CRAM-MD5 Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Shows the CRAM-MD5 SASL mechanism for authentication, which uses HMAC-MD5 for challenge-response. ```smtp AUTH CRAM-MD5 S: 334 C: S: 235 Authentication successful ``` -------------------------------- ### Instantiate SMTPStream with Max Command Length Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPStream.md Create a new SMTPStream instance and configure the maximum length for command lines. This snippet demonstrates setting up the parser and piping incoming socket data to it, along with an example of how to handle received commands. ```javascript const { SMTPStream } = require('smtp-server'); const parser = new SMTPStream({ maxCommandLength: 8192 }); parser.oncommand = (command, callback) => { console.log('Received command:', command.toString()); callback(); }; socket.pipe(parser); ``` -------------------------------- ### Server with Message Size Limits Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt This example shows how to configure the SMTP server to enforce message size limits. It uses the `maxAllowedBytes` option to set the limit and demonstrates real-time checking. ```javascript import { SMTPServer } from 'smtp-server'; const server = new SMTPServer({ // Max message size in bytes (e.g., 10MB) maxAllowedBytes: 10 * 1024 * 1024, onData: (stream, session, callback) => { let size = 0; stream.on('data', (chunk) => { size += chunk.length; if (size > server.options.maxAllowedBytes) { // Abort stream if size limit is exceeded stream.destroy(new Error('Message size exceeded')); } }); stream.on('end', () => { console.log(`Message accepted, size: ${size} bytes`); callback(null, 'Message accepted'); }); } }); server.listen(25, () => { console.log('SMTP server listening on port 25 with size limits'); }); ``` -------------------------------- ### Xtext Parameter Decoding Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/errors.md Shows how parameters encoded with xtext (RFC 3461) are decoded. Control characters in decoded values will cause rejection. ```plaintext ENVID=test+2Bvalue → decoded to: test+value ``` -------------------------------- ### Address Validation Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Demonstrates how addresses are parsed from MAIL FROM commands and how to validate them in the onMailFrom handler. Supports various address formats including SIZE arguments. ```javascript // Input: MAIL FROM: SIZE=1024 // Parsed as: { address: 'user@example.com', args: { SIZE: 1024 } } // Can reject in handler: server.onMailFrom = (address, session, callback) => { if (isBlacklisted(address.address)) { return callback(new Error('Sender rejected')); } callback(); }; ``` -------------------------------- ### Configure Connection Timeout Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/errors.md Set the duration of socket idleness before the connection is closed. This example sets the timeout to 5 minutes. ```javascript { socketTimeout: 300000 // 5 minutes } ``` -------------------------------- ### EHLO Command Example with Capabilities Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Illustrates an Extended SMTP greeting using the EHLO command, which includes advertisement of server capabilities. This is used for extended SMTP communication. ```smtp C: EHLO mail.example.com S: 250-mail.server.com Nice to meet you, [192.0.2.1] S: 250-PIPELINING S: 250-8BITMIME S: 250-SMTPUTF8 S: 250-SIZE 52428800 S: 250-ENHANCEDSTATUSCODES S: 250-AUTH PLAIN LOGIN CRAM-MD5 S: 250-STARTTLS S: 250 XCLIENT NAME ADDR PORT PROTO HELO LOGIN ``` -------------------------------- ### Per-Domain TLS (SNI) Configuration Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt This example demonstrates how to configure the SMTP server for per-domain TLS using Server Name Indication (SNI). It allows the server to present different certificates based on the domain name requested by the client. ```javascript import { SMTPServer } from 'smtp-server'; import fs from 'fs'; const server = new SMTPServer({ // SNI configuration SNICallback: (servername, callback) => { if (servername === 'example.com') { callback(null, { key: fs.readFileSync('path/to/example.com.key'), cert: fs.readFileSync('path/to/example.com.cert') }); } else if (servername === 'another.com') { callback(null, { key: fs.readFileSync('path/to/another.com.key'), cert: fs.readFileSync('path/to/another.com.cert') }); } else { // Default certificate or error callback(new Error('No certificate found for this server name')); } }, secure: true, // Enable TLS onData: (stream, session, callback) => { console.log(`Receiving message for ${session.remoteAddress} with SNI: ${session.tlsSession.servername}`); stream.pipe(process.stdout); stream.on('end', () => callback(null, 'Message accepted')); } }); server.listen(465, () => { console.log('SMTP server listening on port 465 with SNI support'); }); ``` -------------------------------- ### HELO Command Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Demonstrates a basic SMTP greeting using the HELO command. This command is used for simple client identification and does not support extended features. ```smtp C: HELO mail.example.com S: 250 mail.server.com Nice to meet you, [192.0.2.1] ``` -------------------------------- ### Custom Resolver Usage Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Example showing how to configure the SMTP server to use a custom DNS resolver. This is useful for environments with specific DNS requirements or when using a custom DNS service. ```javascript import { SMTPServer } from 'smtp-server'; import dns from 'dns'; // Custom DNS resolver function const customResolver = (host, options, callback) => { // Example: Use Google's public DNS server dns.setServers(['8.8.8.8', '8.8.4.4']); dns.resolveMx(host, (err, addresses) => { dns.setServers(undefined); // Reset to default servers callback(err, addresses); }); }; const server = new SMTPServer({ // Use the custom resolver for MX lookups resolveMx: customResolver, onData: (stream, session, callback) => { console.log('Receiving message with custom DNS resolver'); stream.pipe(process.stdout); stream.on('end', () => callback(null, 'Message accepted')); } }); server.listen(25, () => { console.log('SMTP server listening on port 25 with custom DNS resolver'); }); ``` -------------------------------- ### Implement Custom DNS Reverse Resolver Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Provide a custom resolver object with a `reverse` method to handle reverse DNS lookups. This example uses Node.js's built-in `dns.promises` module. ```javascript const dns = require('dns').promises; { resolver: { reverse: (address, callback) => { dns.reverse(address) .then(hostnames => callback(null, hostnames)) .catch(err => callback(err)); } } } ``` -------------------------------- ### startDataMode Method Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPStream.md Switches the stream from command mode to data mode. It returns a Readable PassThrough stream that emits the message data and provides properties to monitor byte length and size limits. ```APIDOC ## Methods ### startDataMode(maxBytes) Switches the stream from command mode to data mode and returns the output stream. ```javascript startDataMode([maxBytes]) ``` #### Parameters * **maxBytes** (number) - Optional. Maximum bytes allowed. ### Returns A Readable PassThrough stream with the following properties: - `byteLength` - bytes received so far - `sizeExceeded` - boolean, true if exceeded maxBytes - Standard stream events: 'data', 'end', 'error' **Details:** - In data mode, dots at the start of lines are unescaped (RFC 5321). - The stream ends when a line containing only a dot (`.`) is received. - Both `byteLength` and `sizeExceeded` are updated in real-time as data arrives. - Applications can monitor these properties to detect oversized messages mid-transfer. ### Example ```javascript const dataStream = parser.startDataMode(10 * 1024 * 1024); dataStream.on('data', (chunk) => { if (dataStream.sizeExceeded) { console.log('Message exceeds size limit'); } }); dataStream.on('end', () => { console.log(`Message complete: ${dataStream.byteLength} bytes`); }); ``` ``` -------------------------------- ### Constructor Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPStream.md Initializes a new SMTPStream instance. It can be configured with options to set limits on command length. ```APIDOC ## Constructor ```javascript new SMTPStream([options]) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **options** (object) - Optional. Stream options. * **maxCommandLength** (number) - Optional. Max bytes per command line (default: 4096). ### Returns * SMTPStream instance ### Example ```javascript const { SMTPStream } = require('smtp-server'); const parser = new SMTPStream({ maxCommandLength: 8192 }); parser.oncommand = (command, callback) => { console.log('Received command:', command.toString()); callback(); }; socket.pipe(parser); ``` ``` -------------------------------- ### SMTPConnection close() Method Example Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Immediately terminate the current SMTP connection using the close method. ```javascript connection.close(); ``` -------------------------------- ### Initialize SMTPServer with Options Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Pass an options object to the SMTPServer constructor to configure its behavior. ```javascript const server = new SMTPServer({ // options here }); ``` -------------------------------- ### Handle New Client Connection Event Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Listen for the 'connect' event to be notified when a new client successfully connects to the server. ```javascript server.on('connect', (connectionData) => { console.log('Client connected:', connectionData); }); ``` -------------------------------- ### Create Basic SMTP Server Source: https://github.com/nodemailer/smtp-server/blob/master/examples/readme.md Sets up a basic SMTP server that listens on port 25. It disables STARTTLS and AUTH to allow authentication in clear text and prints incoming email data to standard output. ```javascript // smtp.js const { SMTPServer } = require('smtp-server'); const server = new SMTPServer({ // disable STARTTLS to allow authentication in clear text mode disabledCommands: ['STARTTLS', 'AUTH'], logger: true, onData(stream, session, callback) { stream.pipe(process.stdout); // print message to console stream.on('end', callback); } }); server.listen(25); ``` -------------------------------- ### HELP Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Provides help information by returning an RFC reference. The command parameter is ignored. ```APIDOC ## HELP ### Description Returns RFC reference. ### Command Format: ``` HELP [command] ``` ### Parameters: - **command** (string) - Optional - The command to get help for (ignored). ### Response: - `214 See https://tools.ietf.org/html/rfc5321 for details` ### Notes: - Parameter ignored - Always returns same message ``` -------------------------------- ### new SMTPServer(options) Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Creates a new SMTP server instance with configurable options for behavior and security. ```APIDOC ## new SMTPServer(options) ### Description Creates a new SMTP server instance. ### Parameters #### Request Body - **options** (object) - Optional - Configuration object for server behavior. ### Request Example ```javascript const { SMTPServer } = require('smtp-server'); const server = new SMTPServer({ secure: false, logger: true, maxClients: 100 }); server.listen(25, '0.0.0.0'); ``` ``` -------------------------------- ### XOAUTH2 Authentication Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Example of the AUTH XOAUTH2 command format for OAuth2 Bearer token authentication. Requires a TLS connection and prior HELO/EHLO. ```smtp AUTH XOAUTH2 ``` -------------------------------- ### Handle Secure Connection Upgrade Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md Sets up a handler that is invoked immediately after a connection has been upgraded to a secure TLS connection via STARTTLS. It allows for post-upgrade actions or logging. ```javascript server.onSecure = (socket, session, callback) => { console.log('Connection upgraded to TLS'); callback(); }; ``` -------------------------------- ### SMTPConnection send() Method Examples Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Use the send method to transmit SMTP responses to the client. Supports single-line, multi-line, and enhanced status codes. ```javascript // Single line response connection.send(250, 'OK'); ``` ```javascript // Multi-line response connection.send(250, ['PIPELINING', 'ENHANCEDSTATUSCODES', 'SIZE 10485760']); ``` ```javascript // With context for enhanced status codes connection.send(250, 'Message accepted', 'DATA_OK'); ``` -------------------------------- ### SMTPConnection init() Method Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Initializes the connection, setting up listeners and the greeting sequence. This method is called automatically and not typically by applications. ```javascript init() ``` -------------------------------- ### Handling Oversized Messages with Stream Properties Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/types.md An example of how to use `stream.sizeExceeded` to detect and abort oversized messages during data transmission, returning an appropriate error code. ```javascript onData(stream, session, callback) { stream.on('data', chunk => { if (stream.sizeExceeded) { // Message is oversized, can abort stream.destroy(); } }); stream.on('end', () => { if (stream.sizeExceeded) { const err = new Error('Message too large'); err.responseCode = 552; return callback(err); } callback(null, 'OK'); }); } ``` -------------------------------- ### TLS/STARTTLS Server Configuration Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Set up the SMTP server to use TLS for secure connections. The 'needsUpgrade' option enables STARTTLS, and 'key' and 'cert' must be provided. The onSecure callback is invoked when the connection is upgraded. ```javascript const fs = require('fs'); const server = new SMTPServer({ needsUpgrade: true, // Not secure by default key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem'), onSecure: (socket, session, callback) => { console.log('Connection upgraded to TLS'); callback(); } }); ``` -------------------------------- ### Handle Connection Ready Event Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Use the 'connect' event to determine when the connection is fully established and ready to accept email transactions. This event fires after any initial handshake commands like XCLIENT or XFORWARD. ```javascript connection.on('connect', (data) => { console.log('Connection ready'); }); ``` -------------------------------- ### Import SMTPServer Class Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Import the main SMTPServer class from the 'smtp-server' module to create and configure an SMTP server instance. ```javascript const { SMTPServer } = require('smtp-server'); ``` -------------------------------- ### Enable Default Console Logging Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Enable Nodemailer's default console logger for the SMTP server. This is a simple way to get basic logging output. ```javascript { logger: true // Use Nodemailer's default console logger } ``` -------------------------------- ### Disable SMTP Commands Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPConnection.md Configure the SMTPServer to disable specific commands by passing an array of command names to the 'disabledCommands' option during initialization. This example disables VRFY and EXPN. ```javascript new SMTPServer({ disabledCommands: ['VRFY', 'EXPN'] }) ``` -------------------------------- ### STARTTLS Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Upgrades the current connection to an encrypted TLS connection. This must be done before authentication on non-TLS connections unless insecure authentication is allowed. ```APIDOC ## STARTTLS ### Description Upgrades connection to encrypted TLS. ### Command Format: ``` STARTTLS ``` ### Parameters: No parameters. ### Response: - `220 Ready to start TLS` - Upgrade initiated - `503 TLS already active` - Already using TLS - `501 Syntax error: STARTTLS` - Parameters sent (invalid) ### Effect: - Socket upgraded to TLS - Cipher and protocol negotiated - Connection continues encrypted - Feature list re-advertised in next EHLO ### Application Handler: ```javascript onSecure(socket, session, callback) ``` ### Example: ``` C: STARTTLS S: 220 Ready to start TLS (TLS handshake) C: EHLO mail.example.com S: 250 ... (features re-advertised) ``` ### Notes: - Must be before AUTH on non-TLS connections (unless `allowInsecureAuth`) - Socket timeout stays in effect during handshake ``` -------------------------------- ### Application Handler for STARTTLS Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md JavaScript function signature for handling the STARTTLS command, which upgrades the socket to a secure TLS connection. ```javascript onSecure(socket, session, callback) ``` -------------------------------- ### STARTTLS Command Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md The STARTTLS command upgrades the connection to an encrypted TLS connection. It must be used before AUTH on non-TLS connections unless insecure auth is allowed. ```smtp STARTTLS ``` -------------------------------- ### Switch to Data Mode and Process Message Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPStream.md Initiate data mode using 'startDataMode' with an optional maximum byte limit. The returned stream provides 'byteLength' and 'sizeExceeded' properties for real-time monitoring. Event listeners can handle data reception and completion. ```javascript const dataStream = parser.startDataMode(10 * 1024 * 1024); dataStream.on('data', (chunk) => { if (dataStream.sizeExceeded) { console.log('Message exceeds size limit'); } }); dataStream.on('end', () => { console.log(`Message complete: ${dataStream.byteLength} bytes`); }); ``` -------------------------------- ### Configure Proxy Protocol and XCLIENT/XFORWARD Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Enable PROXY protocol for specific IP ranges and activate XCLIENT/XFORWARD extensions for compatibility with mail servers like Postfix. Hosts listed in ignoredHosts will not have PROXY headers logged or enforced. ```javascript { useProxy: ['10.0.0.0/8', '172.16.0.0/12'], // Accept from private networks useXClient: true, ignoredHosts: ['127.0.0.1', '::1'] } ``` -------------------------------- ### SMTP Server Log Output Source: https://github.com/nodemailer/smtp-server/blob/master/examples/readme.md Example log output from the SMTP server during a connection and email reception. Shows connection details, EHLO negotiation, MAIL FROM, RCPT TO, DATA, and QUIT commands. ```log [2016-10-31 11:59:45] INFO: SMTP Server listening on 127.0.0.1:25 [2016-10-31 12:00:01] INFO: [65HrQZWSqi4G] Connection from [127.0.0.1] [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 220 ubuntu-xenial ESMTP [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: EHLO ubuntu-xenial.localdomain [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 250-ubuntu-xenial Nice to meet you, [127.0.0.1] 250-PIPELINING 250-8BITMIME 250-SMTPUTF8 250-AUTH LOGIN PLAIN 250 STARTTLS [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: STARTTLS [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 220 Ready to start TLS [2016-10-31 12:00:01] INFO: [65HrQZWSqi4G] Connection upgraded to TLS [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: EHLO ubuntu-xenial.localdomain [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 250-ubuntu-xenial Nice to meet you, [127.0.0.1] 250-PIPELINING 250-8BITMIME 250-SMTPUTF8 250 AUTH LOGIN PLAIN [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: MAIL From: AUTH=ubuntu@ubuntu-xenial.localdomain [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 250 Accepted [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: RCPT To: [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 250 Accepted [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: DATA [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 354 End data with . Received: (from ubuntu@localhost) by ubuntu-xenial.localdomain (8.15.2/8.15.2/Submit) id u9VC00kF021723 for test@localhost; Mon, 31 Oct 2016 12:00:00 GMT Date: Mon, 31 Oct 2016 12:00:00 GMT From: Ubuntu Message-Id: <201610311200.u9VC00kF021723@ubuntu-xenial.localdomain> Subject: Terminal Email Send Email Content line 1 Email Content line 2 [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: <390 bytes of DATA> [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 250 OK: message queued [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] C: QUIT [2016-10-31 12:00:01] DEBUG: [65HrQZWSqi4G] S: 221 Bye [2016-10-31 12:00:01] INFO: [65HrQZWSqi4G] Connection closed to [127.0.0.1] ``` -------------------------------- ### Configure Authentication and Data Event Handlers Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Set up event handlers for authentication attempts (`onAuth`) and incoming email data (`onData`). The `onAuth` handler validates credentials, while `onData` processes the email stream. ```javascript { onAuth: (auth, session, callback) => { if (auth.username === 'user' && auth.password === 'pass') { return callback(null, { user: 'userid' }); } return callback(new Error('Invalid')); }, onData: (stream, session, callback) => { stream.on('end', () => callback(null, 'OK')); } } ``` -------------------------------- ### LMTP Server with Per-Recipient Handling Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Demonstrates setting up an LMTP server that supports per-recipient responses. This is useful for local mail delivery scenarios where specific feedback for each recipient is needed. ```javascript import { SMTPServer } from 'smtp-server'; const server = new SMTPServer({ // Enable LMTP support lmtp: true, onData: (stream, session, callback) => { // session.rcptTo contains an array of recipients console.log(`Receiving message for recipients: ${session.rcptTo.join(', ')}`); stream.pipe(process.stdout); stream.on('end', () => { // Example: Respond differently based on recipient const responses = session.rcptTo.map(recipient => { if (recipient.includes('invalid')) { return { recipient: recipient, code: 550, message: 'Recipient address rejected' }; } else { return { recipient: recipient, code: 250, message: 'OK' }; } }); callback(null, responses); }); } }); server.listen(2025, () => { console.log('LMTP server listening on port 2025'); }); ``` -------------------------------- ### DATA - Message Content Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md Sends the actual message content, including headers and body. The server expects message content to be terminated by a line containing only a dot (.). RFC 5321 dot-escaping is applied to lines starting with a dot. ```APIDOC ## DATA ### Description Sends the actual message content, including headers and body. The server expects message content to be terminated by a line containing only a dot (.). RFC 5321 dot-escaping is applied to lines starting with a dot. ### Method DATA ### Endpoint N/A (SMTP Command) ### Parameters No parameters. ### Request Example ``` C: DATA S: 354 Start mail input; end with . C: From: sender@example.com C: To: recipient@example.com C: Subject: Test C: C: This is a test message C: . S: 250 OK: message queued ``` ### Response #### Success Response (250 OK) - Message accepted and queued #### Error Responses (SMTP) - `451 Local processing error` - Server error - `452 Insufficient system storage` - Quota/storage error - `552 Exceeds fixed maximum message size` - Message too large - `554 Transaction failed` - Generic failure #### Application Handler ```javascript onData(stream, session, callback) ``` The `stream` object provides `byteLength`, `sizeExceeded`, `on('data', chunk)`, and `on('end')`. ``` -------------------------------- ### Configure TLS/Security Settings Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Configure TLS requirements, certificate paths, and TLS version constraints. ```javascript { secure: true, key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), minVersion: 'TLSv1.2', sniOptions: { 'example.com': { key: fs.readFileSync('example.key'), cert: fs.readFileSync('example.crt') } } } ``` -------------------------------- ### Configure Connection Limits Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Set limits for concurrent connections and commands before authentication. ```javascript { maxClients: 100, socketTimeout: 120000 } ``` -------------------------------- ### HELP Command Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md The HELP command returns a standard RFC reference URL. It ignores any command parameter provided and always returns the same message. ```smtp HELP [command] ``` -------------------------------- ### XFORWARD Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md The XFORWARD command allows for forwarding information to be set, providing context about the client's origin. It is a Postfix extension and requires `useXForward: true` in server options. ```APIDOC ## XFORWARD - Forwarding Information ### Description Postfix extension for forwarding metadata. Logs additional forwarding context and does not change the connection. ### Method N/A (SMTP Command) ### Endpoint N/A (SMTP Command) ### Parameters #### Command Format XFORWARD NAME= ADDR= PORT= PROTO= HELO= IDENT= SOURCE= #### Command Parameters - **NAME** (string) - Client hostname - **ADDR** (string) - Client IP address - **PORT** (number) - Client port - **PROTO** (string) - Protocol - **HELO** (string) - HELO/EHLO hostname - **IDENT** (string) - IDENT protocol info - **SOURCE** (string) - Source type ### Response - `250 OK` - Forwarding info set - `501 Bad command parameter syntax` - Invalid format - `503 Mail transaction in progress` - Can't use during transaction - `550 Not allowed` - XFORWARD not enabled ### Requirements - `useXForward: true` in server options - Allowed multiple times per connection - Not allowed if MAIL already in progress ### Example ``` C: XFORWARD ADDR=192.0.2.1 NAME=source.example.com HELO=mail.source.com S: 250 OK ``` ``` -------------------------------- ### Simple Echo Server Implementation Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md A basic SMTP server that pipes all incoming email data to standard output and acknowledges receipt. Useful for testing. ```javascript const server = new SMTPServer({ onData: (stream, session, callback) => { stream.pipe(process.stdout); stream.on('end', () => callback(null, 'OK')); } }); server.listen(25); ``` -------------------------------- ### Configure Authentication Methods Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/configuration.md Specify allowed authentication methods and whether authentication is optional. ```javascript { authMethods: ['PLAIN', 'CRAM-MD5'], authOptional: false, authRequiredMessage: 'You must authenticate first' } ``` -------------------------------- ### Basic SMTP Server with SMTPStream Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPStream.md Sets up a basic TCP server that uses SMTPStream to parse incoming SMTP commands and data. It logs commands and the content of DATA sections to the console. ```javascript const net = require('net'); const { SMTPStream } = require('smtp-server'); const server = net.createServer((socket) => { const parser = new SMTPStream(); let inDataMode = false; let dataStream; parser.oncommand = (command, callback) => { let line = command.toString().trim(); if (line.toUpperCase() === 'DATA') { inDataMode = true; dataStream = parser.startDataMode(); dataStream.on('data', (chunk) => { console.log('Message data:', chunk.toString()); }); dataStream.on('end', () => { console.log('Message complete'); inDataMode = false; parser.continue(); callback(); }); } else { console.log('Command:', line); callback(); } }; socket.pipe(parser); }); server.listen(25); ``` -------------------------------- ### onSecure(socket, session, callback) Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/api-reference/SMTPServer.md An overridable event handler called after STARTTLS completes, allowing actions on the now secure connection. ```APIDOC ## onSecure(socket, session, callback) ### Description Called after STARTTLS completes and the connection is now secure. ### Parameters #### Request Body - **socket** (object) - Required - TLS socket object - **session** (object) - Required - Session object - **callback** (function) - Required - Must be called; pass error to reject ### Example ```javascript server.onSecure = (socket, session, callback) => { console.log('Connection upgraded to TLS'); callback(); }; ``` ``` -------------------------------- ### Postfix XFORWARD Extension Configuration Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Enable Postfix XFORWARD extension support to allow clients to specify connection details like IP address and hostname. ```javascript new SMTPServer({ useXForward: true // Client sends: XFORWARD ADDR=192.0.2.1 NAME=source.example.com }) ``` -------------------------------- ### Run SMTP Server and Send Email Source: https://github.com/nodemailer/smtp-server/blob/master/examples/readme.md Commands to run the SMTP server in the background and send a test email using the 'sendmail' command. Requires root privileges to listen on port 25. ```bash sudo node smtp.js & sendmail test@localhost < email.txt ``` -------------------------------- ### Configuration Options Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/GENERATION_REPORT.txt Overview of server configuration options available for customizing SMTP server behavior. ```APIDOC ## Server Configuration Options ### Description This section outlines the various options available for configuring the SMTP server's behavior, security, and network settings. ### Key Options - **`name`**: The hostname of the server. - **`port`**: The port number the server listens on. - **`logger`**: An instance of a logger for server events. - **`disabledCommands`**: An array of commands to disable. - **`maxAllowedUnauthenticatedCommands`**: Maximum commands before authentication. For a complete list and detailed explanations, please consult the `configuration.md` file. ``` -------------------------------- ### Postfix XCLIENT Extension Configuration Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/README.md Enable Postfix XCLIENT extension support to allow clients to specify connection details like IP address and hostname. ```javascript new SMTPServer({ useXClient: true // Client sends: XCLIENT ADDR=192.0.2.1 NAME=source.example.com }) ``` -------------------------------- ### XCLIENT Command Source: https://github.com/nodemailer/smtp-server/blob/master/_autodocs/endpoints.md The XCLIENT command, a Postfix extension, allows overriding connection properties for proxy/load-balancer scenarios. Requires 'useXClient: true' server option. ```smtp XCLIENT NAME= ADDR= PORT= PROTO= HELO= LOGIN= ```