Skip to main content

SMTP Connection

A low-level SMTP client for establishing outbound SMTP connections. This module is the foundation that powers Nodemailer's SMTP transport internally. Use it when you need direct, fine-grained control over the SMTP session lifecycle.

info

SMTPConnection is included with Nodemailer. No additional packages need to be installed.

Usage

1. Import the module

const SMTPConnection = require("nodemailer/lib/smtp-connection");

2. Create a connection instance

const connection = new SMTPConnection(options);

3. Connect to the server

connection.connect(callback);

4. Authenticate (if required)

connection.login(auth, callback);

5. Send a message

connection.send(envelope, message, callback);

6. Close the connection

connection.quit(); // or connection.close()

Options reference

OptionTypeDefaultDescription
hostString'localhost'The hostname or IP address of the SMTP server to connect to.
portNumber587 or 465The port number to connect to. Defaults to 465 when secure is true, otherwise 587. If port 465 is specified, secure defaults to true.
secureBooleanfalseIf true, establishes a TLS connection immediately (implicit TLS). If false, the connection starts unencrypted but can be upgraded to TLS via STARTTLS.
servernameStringhostnameThe TLS server name for SNI (Server Name Indication). Automatically set to host value unless host is an IP address.
nameStringos.hostname()The hostname to identify as when sending EHLO/HELO commands. Falls back to [127.0.0.1] if the system hostname is not a valid FQDN.
localAddressString-The local network interface to bind to for outgoing connections.
connectionTimeoutNumber120000Maximum time in milliseconds to wait for the connection to be established (2 minutes).
greetingTimeoutNumber30000Maximum time in milliseconds to wait for the server greeting after the connection is established (30 seconds).
socketTimeoutNumber600000Maximum time in milliseconds of inactivity before the connection is automatically closed (10 minutes).
dnsTimeoutNumber30000Maximum time in milliseconds to wait for DNS resolution (30 seconds).
loggerBoolean | ObjectfalseSet to true to enable logging to the console, or provide a Bunyan-compatible logger instance for custom logging.
debugBooleanfalseIf true, logs all SMTP traffic (commands and responses) to the logger.
lmtpBooleanfalseIf true, uses the LMTP (Local Mail Transfer Protocol) protocol instead of SMTP.
ignoreTLSBooleanfalseIf true, does not attempt STARTTLS even if the server advertises support for it.
requireTLSBooleanfalseIf true, requires STARTTLS and fails if the upgrade is not successful.
opportunisticTLSBooleanfalseIf true, attempts STARTTLS but continues with an unencrypted connection if the upgrade fails.
tlsObject-Additional options passed directly to Node.js tls.connect() and tls.createSecureContext(). Use this to configure certificates, ciphers, and other TLS settings.
socketnet.Socket-A pre-created socket to use instead of creating a new one. The socket should not yet be connected.
connectionnet.Socket-An already-connected socket to use. Useful for connection pooling or proxy scenarios.
securedBooleanfalseSet to true when providing a socket via the connection option that has already been upgraded to TLS.
allowInternalNetworkInterfacesBooleanfalseIf true, internal (loopback) network interfaces are also taken into account when detecting whether the machine supports IPv4/IPv6 for DNS resolution. Useful for localhost-only environments.
customAuthObject-Custom authentication handlers for non-standard authentication methods (see Custom Authentication).
transactionLogBooleanfalseLike debug, logs SMTP commands and responses to the logger, but without the message content.
componentString'smtp-connection'The component name used in log entries.

Events

SMTPConnection extends Node.js EventEmitter and emits the following events:

EventArgumentsDescription
connect-Emitted when the connection is established and the SMTP handshake completes successfully.
errorErrorEmitted when an error occurs during the connection or SMTP session.
end-Emitted when the connection has been closed.

Methods

connect(callback)

Establishes a connection to the SMTP server. The callback is invoked once, with no arguments, when the connection is ready for commands (after the initial greeting and EHLO/HELO handshake). Connection failures (DNS, TCP, TLS, greeting errors) are not passed to this callback — they are emitted on the 'error' event, so always attach an error listener.

connection.on("error", (err) => {
console.error("Connection failed:", err);
});

connection.connect(() => {
console.log("Connected!");
});

login(auth, callback)

Authenticates with the SMTP server. Only call this method if the server requires authentication. The auth object accepts the following properties:

  • user - The username for authentication
  • pass - The password for authentication
  • method - The authentication method to use (optional). If not specified, XOAUTH2 is used when an oauth2 provider is given; otherwise the first advertised method in the order PLAIN, LOGIN, CRAM-MD5, XOAUTH2 is selected (PLAIN is the fallback)
  • oauth2 - An OAuth2 token provider object for XOAUTH2 authentication
connection.login(
{
user: "username",
pass: "password",
},
(err) => {
if (err) {
console.error("Authentication failed:", err);
return;
}
console.log("Authenticated!");
}
);

send(envelope, message, callback)

Sends an email message. The envelope defines the sender and recipient addresses for the SMTP transaction, while message contains the RFC 5322 formatted email content.

The message parameter can be a String, Buffer, or a readable Stream.

const envelope = {
from: "sender@example.com",
to: ["recipient@example.com"],
};

const message = "From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\n\r\nHello!";

connection.send(envelope, message, (err, info) => {
if (err) {
console.error("Send failed:", err);
return;
}
console.log("Message sent:", info);
});

The callback receives an info object with the following properties:

  • accepted - Array of recipient addresses that were accepted by the server
  • rejected - Array of recipient addresses that were rejected by the server
  • rejectedErrors - Array of Error objects with details for each rejected recipient (only present if at least one recipient was rejected)
  • ehlo - Array of extension lines from the server's EHLO response
  • response - The final response string from the server
  • envelopeTime - Time in milliseconds spent sending the envelope (MAIL FROM and RCPT TO commands)
  • messageTime - Time in milliseconds spent sending the message data
  • messageSize - Size of the sent message in bytes

reset(callback)

Sends the SMTP RSET command to reset the current session state. Use this to abort a message transaction without closing the connection.

connection.reset((err, success) => {
if (err) {
console.error("Reset failed:", err);
return;
}
console.log("Session reset");
});

quit()

Sends the SMTP QUIT command and gracefully closes the connection. The server is notified that the session is ending.

connection.quit();

close()

Closes the connection immediately without sending the QUIT command. Use this for forced disconnection scenarios.

connection.close();

Envelope options

The envelope object defines the SMTP transaction parameters and supports the following properties:

PropertyTypeDescription
fromStringThe sender address used in the MAIL FROM command.
toString[]An array of recipient addresses used in RCPT TO commands.
sizeNumberThe message size in bytes. Used with the SIZE extension to check if the server accepts the message before sending.
use8BitMimeBooleanIf true, requests 8BITMIME encoding when the server supports it.
dsnObjectDelivery Status Notification options (see below).
requireTLSExtensionEnabledBooleanIf true, appends the REQUIRETLS parameter (RFC 8689) to MAIL FROM. Fails with an EREQUIRETLS error if the connection is not secured or the server does not advertise REQUIRETLS.

DSN options

Delivery Status Notifications allow you to receive reports about the delivery status of your message. The DSN object supports these properties:

const envelope = {
from: "sender@example.com",
to: ["recipient@example.com"],
dsn: {
ret: "HDRS", // What to return in DSN: 'HDRS' for headers only, 'FULL' for the complete message
envid: "unique-id-123", // A unique envelope identifier for tracking
notify: "SUCCESS,FAILURE", // When to send DSN: 'NEVER', 'SUCCESS', 'FAILURE', 'DELAY' (comma-separated)
orcpt: "rfc822;original@example.com", // The original recipient address (format: address-type;address)
},
};

Complete example

This example demonstrates the full workflow: connecting, authenticating, sending a message, and closing the connection.

const SMTPConnection = require("nodemailer/lib/smtp-connection");

const connection = new SMTPConnection({
host: "smtp.example.com",
port: 587,
secure: false,
debug: true,
logger: true,
});

connection.on("error", (err) => {
// Connection failures (DNS, TCP, TLS, greeting) arrive here
console.error("Connection error:", err);
});

connection.connect(() => {
connection.login(
{
user: "username",
pass: "password",
},
(err) => {
if (err) {
console.error("Authentication failed:", err);
connection.close();
return;
}

const envelope = {
from: "sender@example.com",
to: ["recipient@example.com"],
};

const message = `From: sender@example.com
To: recipient@example.com
Subject: Test Message
Content-Type: text/plain; charset=utf-8

Hello from SMTPConnection!`;

connection.send(envelope, message, (err, info) => {
if (err) {
console.error("Failed to send:", err);
} else {
console.log("Message sent!");
console.log("Accepted:", info.accepted);
console.log("Rejected:", info.rejected);
console.log("Response:", info.response);
}

connection.quit();
});
}
);
});

Properties

After connecting, you can access the following properties on the connection instance:

PropertyTypeDescription
idStringA unique identifier for this connection instance.
secureBooleanTrue if the connection is using TLS encryption.
authenticatedBooleanTrue if the user has successfully authenticated.
lastServerResponseStringThe most recent response received from the server.
allowsAuthBooleanTrue if the server advertises authentication support in its EHLO response.

Supported authentication methods

SMTPConnection supports the following authentication methods:

  • PLAIN - Sends credentials in base64 encoding
  • LOGIN - Legacy method that sends username and password separately
  • CRAM-MD5 - Challenge-response authentication using MD5 hashing
  • XOAUTH2 - OAuth 2.0 authentication for services like Gmail
  • Custom methods via the customAuth option

If no method is specified, XOAUTH2 is used when an oauth2 provider is given; otherwise the client selects the first method advertised by the server in the order PLAIN, LOGIN, CRAM-MD5, XOAUTH2 (PLAIN is the fallback).


License

MIT-0