New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

Handling Email API Errors: HTTP Status Codes, Retries, Rate Limits and Safe Failure Patterns

How to handle errors from an email sending API: reading 4xx and 5xx responses, which errors to retry, backoff and idempotency, rate limit headers, validation errors, partial failures in batches, logging and alerting.

IR
Written by Ishita Rao
Email Authentication Engineer
Reviewed by Ethan Brooks
  • Published8 Jul 2025
  • Read time6 min
  • Length1,252 words
Share this guide

The hard part of sending mail from code is not the happy path. It is what your application does when the provider answers with an error, when the network drops halfway through a request or when you hit a limit during a busy hour. Naive handling produces two failures: messages that are silently lost, and messages that are sent twice. Customers notice both. A reliable integration classifies every failure, retries only what is safe to retry, backs off sensibly, uses idempotency so that retries cannot duplicate, records enough information to debug and alerts a human when automation cannot recover. This guide sets out that approach for HTTP email APIs. Status codes and field names differ between providers, so check your provider's documentation; the patterns, however, are common. It pairs with idempotency and bulk patterns and rate limits and backoff.

ClassifyClient errors (4xx) usually mean fix the request; server errors (5xx) and timeouts may be retried
Retry safelyUse exponential backoff with jitter and an idempotency key
LimitsRespect 429 and Retry-After; slow down instead of hammering
EscalatePark unrecoverable messages in a dead-letter store and alert

Reading the response

StatusTypical meaningRetry?What to do
200, 201, 202Accepted for processing (not the same as delivered)NoStore the message ID returned. Delivery results arrive later by event
400Malformed request or validation errorNoLog the error body; fix the payload (missing field, invalid address, bad template data)
401Missing or invalid credentialsNoCheck the key and environment; alert; do not loop
403Key lacks permission, domain not verified, or account suspendedNoReview permissions and account status. See API key security
404Endpoint or resource not found, such as a template IDNoFix the identifier or URL
409Conflict, often a duplicate idempotency key with a different bodyNoCheck your keying logic
413Payload too largeNoReduce attachments or body size. See size limits
422Semantically invalid data, such as a suppressed recipientNoHandle per cause; remove the recipient or correct the data
429Rate limit exceededYes, after waitingHonour Retry-After; slow the send rate
500, 502, 503, 504Provider fault, overload or gateway timeoutYesRetry with backoff; check the provider status page
Network timeout or resetUnknown outcome: the request may or may not have been processedYes, with idempotencyRetry using the same key so duplicates are ignored

A success response from a sending API usually means "accepted into the queue". It does not mean the message reached the inbox. Bounces and deferrals come later through events. See webhooks vs polling and message lifecycle.

Retry design

  1. Retry only what is retryable: 429, 5xx and network failures. Never retry 4xx errors other than 429 without changing the request.
  2. Use exponential backoff with jitter. Wait 1 second, then 2, 4, 8 and so on up to a limit, adding random variation so that many workers do not retry in step.
  3. Cap attempts and total time. A password-reset email that arrives after an hour is nearly useless; set shorter limits for time-sensitive messages and longer for bulk.
  4. Send an idempotency key with each logical message, derived from your own record (for example order ID plus message type). If the first request actually succeeded, the retry returns the original result instead of sending another. If your provider does not support keys, keep your own record of sent message IDs and check it before retrying.
  5. Honour Retry-After and any rate limit headers (remaining requests and reset time) to adapt your pace.
  6. Add a circuit breaker. When a large share of requests fail, stop for a short period instead of adding load to a struggling service.
def send_with_retry(payload, key, max_attempts=5):
    delay = 1
    for attempt in range(1, max_attempts + 1):
        try:
            r = http.post(URL, json=payload, headers={"Idempotency-Key": key}, timeout=10)
        except (Timeout, ConnectionError):
            r = None
        if r is not None and r.status_code < 300:
            return r.json()["id"]
        if r is not None and r.status_code not in (429, 500, 502, 503, 504):
            raise PermanentError(r.status_code, r.text)      # fix the request; do not retry
        wait = float(r.headers.get("Retry-After", delay)) if r is not None else delay
        sleep(wait + random.uniform(0, wait / 2))
        delay = min(delay * 2, 60)
    raise TemporaryError("gave up; move to dead-letter queue")

Rate limits

Providers limit requests per second, messages per day and recipients per call. When you hit a limit, the right answer is to slow down. Smooth your own sending with a queue and a worker pool whose size matches the allowed rate, instead of firing all requests at once. Watch the rate limit headers to adapt dynamically, and spread large campaigns over time. Remember that sending limits at the mailbox providers are separate and enforced after your provider accepts the message. See throttling and connection reuse.

Validation errors

Many 400 and 422 errors concern the data you send. Typical causes and fixes:

CauseFix
Invalid recipient addressValidate before sending and drop or correct the address. See email validation
Unverified sender domain or addressVerify the domain and authenticate it. See verify your sending domain
Missing template variablesCheck template data against the template schema
Recipient on the suppression listTreat as a successful skip, not a failure. See suppression lists
Content too large or attachment type blockedCompress or link to files
Subject or header contains line breaksStrip control characters from user input
Too many recipients in one callSplit into batches within the documented limit

Batch requests and partial failure

Batch endpoints accept many messages in one request. A 200 response may then include a mix of successes and per-item errors. Read the response body, record the result for each item, and retry only the failed items that are retryable. Never treat the whole batch as failed or successful on the status code alone. Keep a mapping from your own message IDs to the items in the batch so that results can be matched even when the provider returns them in a different order.

Logging and observability

  • Log the request ID returned by the provider, your own message ID, the status code and the error code and message, but not the full message body or secrets.
  • Count outcomes by status code and by error type, and graph them. A rise in 4xx errors usually means a deployment changed the payload; a rise in 5xx or timeouts points at the provider or network.
  • Alert on sustained 401 or 403 (credentials or account problems), on 429 rates that persist and on the size of your retry and dead-letter queues.
  • Keep the dead-letter records with the reason, so that someone can fix and resend them. Define who owns that queue.
  • Subscribe to the provider's status page and keep a runbook for provider outages.

Fallbacks and user experience

For critical messages such as sign-in codes, consider a secondary route: show the user a clear message ("We could not send the email, try again in a minute"), offer another channel such as SMS if appropriate, and let them request a resend with sensible limits. For background messages, queue and retry quietly. Avoid showing raw API errors to users. Never swallow errors in a try block that only logs and continues; a missing receipt is a support ticket. See reliable sending queues.

Testing error handling

  1. Use a mock server that returns each status code, slow responses and dropped connections.
  2. Test that retries stop after the limit and that permanent errors do not retry.
  3. Test duplicate protection by forcing a timeout after the provider has accepted the request.
  4. Run a controlled load test that triggers 429 responses. See load testing.
  5. Rehearse the dead-letter procedure.

Reliable email sending is mostly disciplined error handling: classify, retry safely, slow down when asked, record what happened and ask a human only when needed.

Build on a documented API Clear errors, rate limit headers and idempotency support.

Read the API reference

References and further reading

Frequently asked questions

Which HTTP errors should I retry?

429, 500, 502, 503, 504 and network timeouts. Fix the request for other 4xx errors instead of retrying.

Does a 200 response mean the email was delivered?

No. It means the message was accepted. Delivery, bounce and complaint outcomes arrive later through events.

How do I avoid duplicate emails when retrying?

Send an idempotency key derived from your own record so a repeated request returns the original result.

What should I do on a 429 response?

Wait for the Retry-After period, slow your send rate and use a queue to smooth traffic.

How should I handle partial batch failures?

Read per-item results, record each outcome and retry only failed items that are retryable.

Topics#api#errors#retries#rate limits#idempotency
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales