# How to configure SMTP connections correctly (421: Service not available error)

If you're seeing a 421: Service not available error when sending via SMTP relay, your sending software is most likely trying to send too many emails through a single connection. Here's what's happening and how to fix it.

## What causes the 421 error?

Every SMTP connection follows a set sequence:

1\. Connect to MailerSend's mail server

2\. Authenticate with your credentials

3\. Send recipient info and email data (one email = one transaction)

4\. Disconnect

Each connection has a limit of 5 transactions, meaning you can send a maximum of 5 emails per connection. When your software opens a single connection and tries to loop through more than 5 emails before disconnecting, MailerSend closes the connection and returns the 421 error.

This is a common misconfiguration. Many email libraries and sending tools default to reusing a single connection for all outgoing messages, which works fine at low volumes but breaks at scale.

## How to fix it

### Option 1: Configure your software to open multiple connections

Instead of sending all emails over one connection, configure your software to open a new connection for every batch of up to 5 emails. This is the most reliable fix.

How you do this depends on your sending software. Look for settings like:

- Max messages per connection: Set to 5 or fewer

- Connection pooling: Enable this so your software manages multiple connections automatically

- SMTP session reuse: Disable or limit this setting

If you're not sure where to find these settings, check your software's documentation for "SMTP connection limit" or "max emails per session."

Below are configuration examples for some of the most common sending libraries and tools.

#### PHPMailer

By default, PHPMailer opens a new connection for every _send()_ call, which is correct. The problem occurs when _SMTPKeepAlive_ is set to true. This keeps one connection alive across all sends in a loop, which will exceed the 5-transaction limit.

If you're sending in a loop with _SMTPKeepAlive_ enabled, you need to manually close and reopen the connection every 5 emails:

```php
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host       = 'smtp.mailersend.net';
$mail->SMTPAuth   = true;
$mail->Username   = 'your-username';
$mail->Password   = 'your-password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = 587;

// Only enable SMTPKeepAlive if you're managing reconnects manually
$mail->SMTPKeepAlive = true;

$recipients = ['a@example.com', 'b@example.com', /* ... */];
$batchSize  = 5; // Stay within MailerSend's 5-transaction limit

foreach ($recipients as $index => $recipient) {
    $mail->clearAddresses();
    $mail->addAddress($recipient);
    $mail->Subject = 'Your subject';
    $mail->Body    = 'Your message body';

$mail->send();

// Close the connection after every 5 emails and let it reopen on the next send
    if (($index + 1) % $batchSize === 0) {
        $mail->smtpClose();
    }
}

// Always close the connection when done
$mail->smtpClose();
```

**Note:**

If _SMTPKeepAlive_ is false (the default), PHPMailer reconnects on every send automatically, no batching logic needed. Only add the manual close logic if you've explicitly enabled SMTPKeepAlive.

#### WordPress + WP Mail SMTP

WP Mail SMTP uses PHPMailer under the hood. WordPress sites typically send low volumes of transactional emails (form submissions, order confirmations, account emails) where each email is triggered individually. This pattern is less likely to hit the connection limit.

If your site sends bursts of emails (for example, notifying many users at once via a plugin), use WP Mail SMTP's built-in rate limiting to spread sends over time:

1\. In WP Mail SMTP, go to **Settings** \> **Misc**.

2\. Toggle the **Email Rate Limiting** option on.

3\. Set a limit such as 5 emails per minute to stay comfortably within MailerSend's 120 auth requests/minute ceiling.

This throttles or schedules email sending depending on configuration.

#### Nodemailer (Node.js)

Nodemailer's default behavior creates a fresh connection per email, which is safe. The issue arises when connection pooling is enabled ( _pool: true_) with _maxMessages_ set higher than 5. With pooling, Nodemailer reuses connections across multiple sends until _maxMessages_ is reached. If that threshold is above 5, you'll exceed MailerSend's limit.

Set _maxMessages_ to 5 to match MailerSend's per-connection transaction limit:

```javascript
const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  host: 'smtp.mailersend.net',
  port: 587,
  secure: false,
  pool: true,          // Connection pooling is enabled
  maxConnections: 5,   // Up to 5 parallel connections (stay under the 120 auth/min limit when combined)
  maxMessages: 5,      // Close and reopen connection after 5 emails to match MailerSend's limit
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
});
```

**Note:**

Nodemailer's _maxMessages_ defaults to 100, which will immediately exceed the 5-transaction limit if pooling is on. Always set _maxMessages: 5_ when using MailerSend's SMTP relay.

#### smtplib (Python)

Python's smtplib keeps the connection open for as long as the SMTP object exists. If you loop through recipients and call _sendmail()_ more than 5 times on the same connection, you'll hit the limit.

The fix is to reconnect every 5 emails using a batch loop:

```python
import smtplib
import time
from email.mime.text import MIMEText

SMTP_HOST = 'smtp.mailersend.net'
SMTP_PORT = 587
USERNAME  = 'your-username'
PASSWORD  = 'your-password'
BATCH_SIZE = 5  # MailerSend's transaction limit per connection

recipients = ['a@example.com', 'b@example.com', 'c@example.com']  # your full list

# Split recipients into batches of 5
def chunked(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i:i + size]

for batch in chunked(recipients, BATCH_SIZE):
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp:
        smtp.starttls()
        smtp.login(USERNAME, PASSWORD)
        for recipient in batch:
            msg = MIMEText('Your message body')
            msg['Subject'] = 'Your subject'
            msg['From']    = 'you@yourdomain.com'
            msg['To']      = recipient
            smtp.sendmail('you@yourdomain.com', recipient, msg.as_string())
    # Connection closes automatically at end of `with` block
    # Optional: add a short delay between batches to avoid hitting auth rate limits
    time.sleep(0.5)
```

**Note:**

Using Python's _with_ statement ensures the connection closes cleanly after each batch. The _time.sleep()_ call helps if you're sending large volumes. Without it, rapid reconnects can trigger the 120 auth requests/minute rate limit.

#### Django (django.core.mail)

Django's email backend creates a new connection per _send\_mail()_ call by default, which is safe. For sending to multiple recipients efficiently, use _send\_mass\_mail()_ or open a connection manually with _get\_connection()_, but close it every 5 messages:

```python
from django.core.mail import get_connection, EmailMessage
import time

recipients = ['a@example.com', 'b@example.com', 'c@example.com']  # your full list
BATCH_SIZE = 5

def chunked(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i:i + size]

for batch in chunked(recipients, BATCH_SIZE):
    connection = get_connection()
    connection.open()
    messages = [\
        EmailMessage(\
            subject='Your subject',\
            body='Your message body',\
            from_email='you@yourdomain.com',\
            to=[recipient],\
            connection=connection,\
        )\
        for recipient in batch\
    ]
    connection.send_messages(messages)
    connection.close()
    time.sleep(0.5)  # Throttle between batches
```

#### Jakarta Mail/JavaMail (Java)

The standard _Transport.send()_ pattern in JavaMail opens and closes a connection per email by default, which is safe. The limit is most likely to be hit when a _Transport_ object is reused across many sends in a loop.

Use _transport.sendMessage()_ in batches of 5, closing and reconnecting between batches:

```javascript
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.*;

public class BatchEmailSender {

private static final int BATCH_SIZE = 5; // MailerSend's transaction limit

public static void main(String[] args) throws Exception {
        String host     = "smtp.mailersend.net";
        String username = "your-username";
        String password = "your-password";

Properties props = new Properties();
        props.put("mail.smtp.auth",            "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host",            host);
        props.put("mail.smtp.port",            "587");

Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

List recipients = List.of("a@example.com", "b@example.com", "c@example.com");

for (int i = 0; i < recipients.size(); i += BATCH_SIZE) {
            List batch = recipients.subList(i, Math.min(i + BATCH_SIZE, recipients.size()));

// Open a fresh connection for each batch
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);

for (String recipient : batch) {
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress("you@yourdomain.com"));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
                message.setSubject("Your subject");
                message.setText("Your message body");
                transport.sendMessage(message, message.getAllRecipients());
            }

transport.close(); // Close after each batch of 5
            Thread.sleep(500); // Optional: throttle between batches
        }
    }
}
```

### Option 2: Implement proper send throttling

Even with multiple connections, you'll need to stay within the authentication rate limit of 120 requests per minute. If your software opens connections too quickly, you'll hit a different rate limit.

To stay well within limits:

- Introduce a short delay between connection attempts

- Don't send all emails simultaneously. Instead, spread them out over time

- Use a queue or job system if you're sending large volumes

With correct configuration, you can send up to 600 emails per minute (120 connections × 5 transactions each).

## Sending marketing emails

If you're hitting this error because you're sending bulk campaigns, like newsletters, promotional emails, or announcements, MailerSend isn't the right tool for that. Our SMTP relay is designed for transactional emails: password resets, order confirmations, account notifications and other programmatically triggered, one-to-one messages.

For marketing campaigns, use [MailerLite](https://www.mailerlite.com/) instead. It's built for bulk, promotional sending with the features (unsubscribe management, list segmentation, analytics) that marketing emails require. Using our SMTP relay for bulk sends will consistently run into connection and rate limits, regardless of configuration.

## Current SMTP limits

Here's a full breakdown of the limits in place:

- Connections per IP per minute: 300 per 60 seconds

- Transactions per connection: 5 (default)

- Failed logins per IP per day: 100

- Tracking window: 24 hours

- Block duration: 24 hours
- Consecutive login fails per username + IP: 10

- Tracking window: 90 days

- Block duration: 1 hour
- Consecutive login requests per username: 120 per 60 seconds

**Maximum throughput**: 600 emails per minute when correctly configured (120 connections × 5 transactions).

**Note:**

The authentication limit of 120 requests/minute is the effective ceiling. You'll hit this before reaching the 300 connections/minute limit.

## What to do if you’re still seeing the error

If you've updated your configuration and you're still hitting the 421 error:

1\. Confirm your software is actually opening a new connection after every 5 emails and not just retrying the same connection.

2\. Check whether you're also hitting the 120 authentication requests/minute limit by reviewing your send logs for authentication failures.

3\. Reach out to our support team with your sending logs. We can help identify exactly where the limit is being hit.

## **Need more info?**

Feel free to reach out to support@mailersend.com. A member of our support team will gladly assist you.

- [Getting started: Sending your first email](/content/help/getting-started/index.html)  - [Navigating the app interface](/content/help/navigating-the-dashboard/index.html)
- [Email](/content/help/email/index.html)  - [Add and verify a sending domain](/content/help/how-to-verify-and-authenticate-a-sending-domain/index.html)
  - [How to merge multiple SPF records](/content/help/how-to-merge-spf-records/index.html)
  - [Start sending transactional emails](/content/help/how-to-start-sending-emails/index.html)
  - [SMTP relay](/content/help/smtp-relay/index.html)
  - [Testing email sending with blackhole recipients](/content/help/how-to-test-email-sending-in-mailersend/index.html)
  - [Email Activity](/content/help/activity/index.html)
  - [Analytics](/content/help/analytics/index.html)
  - [Bulk email sending](/content/help/schedule-bulk-emails-with-the-bulk-endpoint/index.html)
  - [Custom headers](/content/help/custom-headers/index.html)
  - [Custom unsubscribe headers](/content/help/how-to-add-a-custom-unsubscribe-header/index.html)
  - [Sending domains](/content/help/what-is-a-sending-domain/index.html)
  - [Domain reputation](/content/help/domain-reputation/index.html)
  - [Domain tracking options](/content/help/domain-tracking-options/index.html)
  - [Personalization in emails](/content/help/how-to-use-personalization/index.html)
  - [Sender identities](/content/help/send-email-on-behalf-of-clients/index.html)
  - [Split Testing](/content/help/a-b-split-testing/index.html)
  - [Surveys](/content/help/how-to-add-a-survey-to-your-emails/index.html)
  - [Tagging emails](/content/help/how-to-tag-emails/index.html)
  - [Templates](/content/help/how-to-create-a-template/index.html)
  - [How to translate email templates automatically](/content/help/template-translations/index.html)
  - [How to configure SMTP connections correctly (421: Service not available error)](/content/help/smtp-configuration-421-error/index.html)
  - [How to enable Google Email Actions & Highlights](/content/help/enable-google-email-actions/index.html)
  - [How transactional emails work](/content/help/how-transactional-emails-work/index.html)
  - [The difference between transactional emails and marketing emails](/content/help/transactional-email-vs-marketing-email/index.html)
- [SMS](/content/help/sms/index.html)  - [Purchase an SMS phone number](/content/help/how-to-purchase-an-sms-phone-number/index.html)
  - [Start sending SMS](/content/help/how-to-start-sending-sms/index.html)
  - [SMS: How to handle opt-in and opt-out](/content/help/sms-how-to-handle-opt-in-and-opt-out/index.html)
  - [SMS verification and usage limits](/content/help/sms-verification-and-limits/index.html)
- [WhatsApp](/content/help/whatsapp/index.html)  - [Getting started with WhatsApp](/content/help/getting-started-with-whatsapp/index.html)
  - [How to connect and use the WhatsApp sandbox](/content/help/whatsapp-sandbox/index.html)
  - [Managing WhatsApp Business phone numbers](/content/help/managing-whatsapp-business-phone-numbers/index.html)
  - [How to create and manage WhatsApp templates](/content/help/how-to-create-and-manage-whatsapp-templates/index.html)
  - [WhatsApp message activity](/content/help/whatsapp-message-activity/index.html)
  - [WhatsApp inbound messaging: How it works and how to set it up](/content/help/whatsapp-inbound-messaging/index.html)
- [Developer tools](/content/help/developer-tools/index.html)  - [Managing API tokens](/content/help/managing-api-tokens/index.html)
  - [Webhooks](/content/help/webhooks/index.html)
  - [API & SMTP request logs](/content/help/api-smtp-logs/index.html)
  - [REST API response codes](/content/help/rest-api-response-codes/index.html)
- [Deliverability](/content/help/deliverability/index.html)  - [Blocklist monitoring](/content/help/blocklist-monitoring/index.html)
  - [DMARC monitoring](/content/help/dmarc-monitoring/index.html)
  - [How to verify an email list](/content/help/how-to-verify-email-addresses/index.html)
  - [Deferred emails](/content/help/what-are-deferred-bounces/index.html)
  - [Suppressions](/content/help/suppression-list-managing/index.html)
  - [On Hold blocklist](/content/help/on-hold-blocklist/index.html)
  - [Spam complaints](/content/help/spam-complaints/index.html)
  - [403, 422, & 429 errors](/content/help/rate-limits-how-to-reduce-403-422-429-errors/index.html)
  - [What are hard and soft bounces?](/content/help/bounced-emails/index.html)
  - [Improve email deliverability](/content/help/improve-email-deliverability/index.html)
  - [Reduce unsubscribe rates](/content/help/reducing-unsubscribe-rates/index.html)
  - [Account reputation statuses](/content/help/account-reputation-statuses/index.html)
- [Account, billing & add-ons](/content/help/account-settings/index.html)  - [Plans, features and limits](/content/help/plans-features-and-limits/index.html)
  - [Plan add-ons](/content/help/plan-add-ons/index.html)
  - [User management](/content/help/user-management/index.html)
  - [Change password](/content/help/change-password/index.html)
  - [Two-factor authentication](/content/help/two-factor-authentication/index.html)
  - [Switch accounts](/content/help/switch-accounts/index.html)
  - [How to whitelist IPs](/content/help/how-to-whitelist-ips/index.html)
  - [How to add a domain space to your account](/content/help/how-to-add-a-domain-space-to-your-account/index.html)
  - [How to request a dedicated IP](/content/help/how-to-request-dedicated-ip/index.html)
  - [How to set a billing limit on your account](/content/help/how-to-set-a-billing-limit/index.html)
  - [How to change your payment method](/content/help/how-to-change-your-payment-method/index.html)
  - [How to change or cancel your plan](/content/help/how-to-change-or-cancel-your-plan/index.html)
  - [Delete account](/content/help/delete-account/index.html)
  - [VAT Collection for EU Customers](/content/help/vat-collection-eu/index.html)
  - [VAT Collection for UK Customers](/content/help/vat-collection-uk/index.html)
  - [GST Collection for Customers in India](/content/help/gst-collection-india/index.html)
  - [GST Collection for Customers in Canada](/content/help/gst-collection-canada/index.html)
  - [VAT (IVA) Collection for Customers in Chile](/content/help/vat-iva-collection-chile/index.html)
  - [Sandbox mode and the Professional trial](/content/help/sandbox-mode-and-the-professional-trial/index.html)
  - [Sales Tax Collection for Customers in New York](/content/help/sales-tax-collection-for-customers-in-new-york/index.html)
- [Integrations](/content/help/integrations/index.html)  - [How to integrate MailerSend with Zapier](/content/help/how-to-integrate-mailersend-with-zapier/index.html)
  - [How to integrate MailerSend with Supabase](/content/help/how-to-integrate-mailersend-with-supabase/index.html)
  - [How to integrate MailerSend with Airtable](/content/help/how-to-integrate-mailersend-with-airtable/index.html)
  - [How to integrate MailerSend with Slack for email event notifications](/content/help/how-to-integrate-mailersend-with-slack-for-email-event-notifications/index.html)
  - [WordPress](/content/help/how-to-integrate-mailersend-with-wordpress/index.html)
  - [WooCommerce](/content/help/how-to-integrate-mailersend-with-woocommerce/index.html)
  - [How to configure MailerSend on Google Cloud](/content/help/how-to-configure-mailersend-on-google-cloud/index.html)
  - [How to connect MailerSend's MCP with your AI tools](/content/help/how-to-connect-mailersends-mcp/index.html)
- [Agency guides](/content/help/agency-guides/index.html)  - [Creating sub-accounts for clients](/content/help/creating-sub-accounts/index.html)
  - [Sending emails for clients: domains vs. sender identities](/content/help/sender-identities-vs-domains/index.html)
- [API reference ↗](https://developers.mailersend.com/)

- [What causes the 421 error?](/content/help/smtp-configuration-421-error/index.html#what-causes-the-421-error)
- [How to fix it](/content/help/smtp-configuration-421-error/index.html#how-to-fix-it)
- [Option 1: Configure your software to open multiple connections](/content/help/smtp-configuration-421-error/index.html#option-1-configure-your-software-to-open-multiple-connections)
- [PHPMailer](/content/help/smtp-configuration-421-error/index.html#phpmailer)
- [WordPress + WP Mail SMTP](/content/help/smtp-configuration-421-error/index.html#wordpress-wp-mail-smtp)
- [Nodemailer (Node.js)](/content/help/smtp-configuration-421-error/index.html#nodemailer-nodejs)
- [smtplib (Python)](/content/help/smtp-configuration-421-error/index.html#smtplib-python)
- [Django (django.core.mail)](/content/help/smtp-configuration-421-error/index.html#django-djangocoremail)
- [Jakarta Mail/JavaMail (Java)](/content/help/smtp-configuration-421-error/index.html#jakarta-mailjavamail-java)
- [Option 2: Implement proper send throttling](/content/help/smtp-configuration-421-error/index.html#option-2-implement-proper-send-throttling)
- [Sending marketing emails](/content/help/smtp-configuration-421-error/index.html#sending-marketing-emails)
- [Current SMTP limits](/content/help/smtp-configuration-421-error/index.html#current-smtp-limits)
- [What to do if you’re still seeing the error](/content/help/smtp-configuration-421-error/index.html#what-to-do-if-youre-still-seeing-the-error)
