Opening an SMTP connection is expensive. Each new connection needs a TCP handshake, a TLS negotiation, a greeting, an EHLO exchange and an authentication step before a single byte of your message is sent. Sending one message per connection to a relay therefore wastes most of the time on setup and, at volume, also triggers connection-rate limits at the server. Connection pooling and keep-alive fix this by holding connections open and sending many messages through each. This guide explains how SMTP sessions work, how to size a pool, what limits to respect, how to handle failures on a long-lived connection and how to configure the common libraries in Node.js, Python and PHP. The limits that apply on your own account, such as connections per minute and messages per connection, are set by your provider, so check the service documentation and treat the numbers here as starting points.
How an SMTP session works
An SMTP session is a conversation. After the connection and TLS setup, the client authenticates and then repeats a cycle for each message: MAIL FROM, one or more RCPT TO, DATA, the message, and the reply that accepts or rejects it. The protocol allows many such cycles in one session, and the RSET command clears the state if you need to abort a transaction. Closing is done with QUIT. Nothing in the standard requires a new connection per message; this is a habit of simple scripts that call a library function which connects, sends and disconnects. Compare the steps in testing an SMTP connection and the port choices in SMTP ports.
Why pooling matters
| Pattern | What happens | Effect at volume |
|---|---|---|
| One connection per message | Handshake, TLS and login for every message | Slow; may hit connection-rate or login-rate limits; wasteful on both sides |
| One long session, sequential | All messages through a single connection | Good for moderate volume; limited by round trips |
| Small pool of persistent connections | Several sessions in parallel, each reused | Best balance of speed and politeness; needs sizing |
| Very large number of connections | Dozens or hundreds of parallel sessions | Likely to trigger concurrency limits and 421 replies |
Sizing the pool
A pool has two main numbers: how many connections to hold and how many messages to send over each before replacing it. Start small. A pool of two to five connections is enough for most applications; the throughput of a single session is often a few messages per second to a few tens, depending on round-trip time and message size, so a handful of sessions can send tens of thousands of messages per hour. Raise the number only when you are sure that the server accepts it. Providers publish limits such as the maximum number of simultaneous connections per account or per IP, the maximum messages per connection and the maximum recipients per message. Exceeding them produces temporary rejections such as 421 4.7.0 Too many connections or a rate-limit message; see 421 try again later and rate limits, retries and backoff.
- Max connections: keep it below the provider limit, leaving room for other applications that share the account.
- Max messages per connection: recycle each connection after a fixed number (for example 100) so that a half-broken session does not live forever.
- Idle timeout: servers close idle connections after a period, often a few minutes. Close from your side first or send a
NOOPto keep it alive. - Rate limit per second: a throttle prevents bursts that look like abuse.
Node.js with Nodemailer
Nodemailer has a built-in pool. Enable it in the transport options:
const nodemailer = require('nodemailer');
const transport = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // STARTTLS on 587
requireTLS: true,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
pool: true,
maxConnections: 3, // parallel sessions
maxMessages: 100, // messages before a connection is replaced
rateLimit: 10, // messages per rateDelta
rateDelta: 1000 // milliseconds
});
await transport.sendMail({ from: '[email protected]', to: '[email protected]', subject: 'Hello', text: 'Hi' });Create the transport once when the application starts and reuse it. Creating a new transport for each message defeats the pool. Close it with transport.close() on shutdown. See also the Nodemailer guide.
Python with smtplib
The standard library keeps one connection per SMTP object, so reuse the object and send many messages through it. Wrap the loop to reconnect when the server drops the session:
import smtplib, time
from email.message import EmailMessage
def connect():
s = smtplib.SMTP('smtp.example.com', 587, timeout=30)
s.starttls()
s.login('USER', 'PASSWORD')
return s
def send_all(messages, per_conn=100):
s, sent = connect(), 0
for msg in messages:
try:
s.send_message(msg)
except (smtplib.SMTPServerDisconnected, smtplib.SMTPConnectError):
s = connect()
s.send_message(msg)
sent += 1
if sent % per_conn == 0:
s.quit()
s = connect()
s.quit()For parallel sending, give each worker its own connection; do not share one SMTP object between threads. See Python smtplib.
PHP with PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPKeepAlive = true; // keep the session open between sends
foreach ($recipients as $r) {
$mail->clearAddresses();
$mail->addAddress($r['email']);
$mail->Subject = 'Hello';
$mail->Body = 'Hi ' . $r['name'];
$mail->send();
}
$mail->smtpClose();Remember to clear addresses and attachments between messages, or each message will include the previous recipients. See PHPMailer guide.
Handling failures on a reused connection
| Event | Meaning | What to do |
|---|---|---|
| Server disconnected | Idle timeout or server-side recycling | Reconnect and retry the message once |
| 421 reply | Temporary: too many connections or messages, or server busy | Back off, reduce pool size, retry later |
| 4xx on a recipient | Temporary rejection (greylisting, rate limit) | Retry with increasing delay; keep the session |
| 5xx on a recipient | Permanent failure for that address | Do not retry; suppress the address; the session remains usable |
| Authentication error mid-session | Credentials revoked or rate limited | Stop, alert and do not hammer the login |
| Timeout during DATA | Network problem or very large message | Reconnect; make sure the message is not duplicated if the server accepted it |
A key risk is duplicates. If the connection drops after the server accepted the message but before you read the reply, a blind retry sends it twice. For messages where duplicates matter, such as receipts, use an idempotency approach: store a unique message ID in your queue and mark it as sent only when you have the success reply, and consider the Message-ID header as a trace key. See reliable sending queues. An HTTP API with idempotency keys avoids the problem; see SMTP vs API.
Pipelining, TLS and monitoring
Two further features affect speed. The first is command pipelining, an SMTP extension that lets a client send several commands without waiting for each reply. Libraries that support it use it automatically when the server advertises it in the EHLO response, and you rarely need to configure it. The second is TLS session reuse, which reduces the cost of reconnecting when a pool replaces a connection. You gain it for free with most modern libraries. What you should add yourself is monitoring. Track the number of open connections, the time from queue to server acceptance, the share of messages that needed a retry and the count of 421 replies per hour. A rising share of retries is an early warning that you are close to a limit or that the server is under strain. Look at these numbers after every change of pool size so that you tune with evidence instead of guesses.
It is also wise to isolate sending workers from the web request path. A web handler that opens an SMTP connection while a user waits will be slow and will fail when the relay is busy. Put messages on a queue and let a small group of workers, each holding a persistent connection, take them off. This gives you control over the rate, lets you retry without involving the user and keeps the pool size independent of web traffic. Many teams find that this one change removes most of their email-related timeouts, and it prepares the ground for moving high-priority mail to an API later, if you need stronger delivery tracking.
Practical checklist
- Create the transport or connection object once, not per message.
- Start with a pool of two to five connections and one hundred messages per connection.
- Add a rate limit so that a burst cannot exceed your provider limits.
- Reconnect on disconnect and retry once; use backoff for 4xx replies.
- Treat permanent errors per recipient, not per connection.
- Log the session ID, the remote reply and the message ID for each send.
- Close the pool on shutdown so that sessions end with QUIT.
With a sensible pool, a modest server can send a large queue quickly without ever looking like a flood. The goal is steady throughput inside your provider's limits, with clean failure handling.
Send at volume over SMTP Authenticated SMTP relay with TLS on port 587 and documented limits.
References and further reading
Frequently asked questions
Can I send many emails over one SMTP connection?
Yes. SMTP allows many MAIL FROM, RCPT TO and DATA cycles in one session. Pooling uses this to avoid repeated handshakes.
How many connections should I open?
Start with two to five and stay below the limits published by your provider. More connections raise the risk of 421 rejections.
Why does my connection drop after a few minutes?
Servers close idle sessions after a timeout. Reconnect on disconnect, or send NOOP to keep the session alive.
How do I avoid duplicate emails when retrying?
Record success only when the server replies 250, use unique message IDs, and prefer an API with idempotency keys for critical messages.
Does PHPMailer support keep-alive?
Yes. Set SMTPKeepAlive to true, clear addresses between messages and call smtpClose() at the end.