Home / Developers / Python

Email verification API for Python

Verify one address or a whole list from Python in a few lines. The API is plain HTTPS and JSON: no SDK needed, one bearer key, and the examples below are complete and runnable.

Updated 2026-10-18

TL;DR

  • The Mail Exchange API is plain HTTPS and JSON at https://mailexchange.com/api/v1. No SDK needed.
  • POST /verify checks one address and usually answers in a few seconds. POST /lists checks up to 100,000 addresses and you poll for the result.
  • Each result has a state: deliverable, risky, undeliverable or unknown. The decision function below turns that into send, separate, skip, remove or retry.
  • Handle three statuses and you are done: 202 (still checking), 402 (out of credits) and 429 (slow down).

Get an API key

Keys are issued on request. Ask for one and we will set you up with free test credits. Every request sends the key as Authorization: Bearer your_key. Keep it in an environment variable, as the examples do, and out of source control. Credit prices are on the pricing page and credits never expire.

What you need

Python 3.8 or newer and the requests library (pip install requests). Nothing else.

The session object reuses the TLS connection, which matters if you loop over a few addresses. The 45 second timeout is deliberate: /verify can hold the connection for around 20 seconds before it gives up and returns 202. If you already use httpx or aiohttp, the calls are identical, only the client changes. For more than a handful of addresses, skip the loop and use the list example below.

Verify one address in Python

Save this as mx_one.py. It defines a small call helper that sends the key, retries on 429, and turns error responses into an exception or error value with the message from the API. Then verify_one posts the address and handles the one tricky case: a slow mail server.

import os
import sys
import time

import requests

BASE = "https://mailexchange.com/api/v1"
API_KEY = os.environ["MAILEXCHANGE_API_KEY"]
session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"


class MXError(Exception):
    def __init__(self, status, message):
        super().__init__(f"HTTP {status}: {message}")
        self.status = status


def call(method, path, retries=4, **kwargs):
    """One API call. Retries 429 with exponential backoff, raises MXError on other errors."""
    for attempt in range(retries + 1):
        r = session.request(method, BASE + path, timeout=45, **kwargs)
        if r.status_code == 429 and attempt < retries:
            time.sleep(2 ** attempt)
            continue
        break
    if r.status_code >= 400:
        try:
            message = r.json().get("error", r.text)
        except ValueError:
            message = r.text
        raise MXError(r.status_code, message)
    return r


def decide(result):
    """Turn a result into an action: send, separate, skip, remove or retry."""
    state, reason = result.get("state"), result.get("reason")
    if state == "deliverable":
        return "send"
    if state == "risky":
        if reason == "low_deliverability":   # catch-all domain
            return "separate"
        return "skip"                         # role address or disposable
    if state == "undeliverable":
        return "remove"
    return "retry"                            # unknown, or still pending


def verify_one(email):
    r = call("POST", "/verify", json={"email": email})
    result = r.json()
    if r.status_code != 202:
        return result
    # 202: the mail server is slow. The check is running and already paid for.
    # Do not post the address again, poll the list instead.
    list_id = result["list_id"]
    for _ in range(36):
        time.sleep(5)
        rows = call("GET", f"/lists/{list_id}/results", params={"limit": 1}).json()["results"]
        if rows and rows[0].get("state") != "pending":
            return rows[0]
    return result  # still pending after 3 minutes: look again later with the same list_id


if __name__ == "__main__":
    try:
        res = verify_one(sys.argv[1])
    except MXError as e:
        sys.exit(f"Mail Exchange error: {e}")
    print(res["email"], res["state"], res.get("reason"), "->", decide(res))

Run it:

MAILEXCHANGE_API_KEY=mx_live_xxx python mx_one.py [email protected]

Typical output looks like [email protected] deliverable accepted_email -> send.

About the 202. Most checks finish within a few seconds. If a mail server is slow, /verify waits about 20 seconds and then returns 202 with {"state": "pending", "list_id": ...}. That check is already running and was already charged. Posting the same address again would start a second check and charge again, so read the result from /lists/{list_id}/results instead, as the code does. More in errors, credits and rate limits.

Read the result and decide what to do

A result is a flat JSON object: email, state, reason, score, and the flags accept_all, role, free, disposable, plus mx. The state is what you branch on. The reason tells you why, and matters for the risky group. The decide function in the code above maps it like this:

statereasondecide() returnsWhy
deliverableaccepted_emailsendThe mail server accepted the mailbox.
riskylow_deliverabilityseparateCatch-all domain. Cannot be confirmed either way. Send carefully or keep apart.
riskylow_quality, disposableskipRole address (info@, sales@) or a throwaway domain.
undeliverablerejected_email, invalid_domain, invalid_emailremoveWill bounce. Drop it.
unknownunavailable_smtp, no_connect, dns_errorretryThe server did not give a clear answer. The credit is refunded.

The function is deliberately small so you can change it. A cold email team might send separate addresses only from established inboxes, as described in catch-all emails and cold email. A signup form might accept risky addresses but block undeliverable ones. The full list of states is in email verification statuses, and how it works explains the six checks behind them.

Verify a list in Python

For more than a handful of addresses, submit one list instead of looping over /verify. You get a list ID straight away, poll GET /lists/{id} until its status is done (or failed), then page through /lists/{id}/results 1,000 rows at a time. Duplicates inside the list are removed and not charged. Save this as mx_list.py with one address per line in emails.txt.

import os
import sys
import time

import requests

BASE = "https://mailexchange.com/api/v1"
API_KEY = os.environ["MAILEXCHANGE_API_KEY"]
session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"


class MXError(Exception):
    def __init__(self, status, message):
        super().__init__(f"HTTP {status}: {message}")
        self.status = status


def call(method, path, retries=4, **kwargs):
    """One API call. Retries 429 with exponential backoff, raises MXError on other errors."""
    for attempt in range(retries + 1):
        r = session.request(method, BASE + path, timeout=45, **kwargs)
        if r.status_code == 429 and attempt < retries:
            time.sleep(2 ** attempt)
            continue
        break
    if r.status_code >= 400:
        try:
            message = r.json().get("error", r.text)
        except ValueError:
            message = r.text
        raise MXError(r.status_code, message)
    return r


def decide(result):
    """Turn a result into an action: send, separate, skip, remove or retry."""
    state, reason = result.get("state"), result.get("reason")
    if state == "deliverable":
        return "send"
    if state == "risky":
        if reason == "low_deliverability":   # catch-all domain
            return "separate"
        return "skip"                         # role address or disposable
    if state == "undeliverable":
        return "remove"
    return "retry"                            # unknown, or still pending


def verify_list(emails, poll_seconds=5):
    created = call("POST", "/lists", json={"emails": emails, "name": "python-example"}).json()
    list_id = created["id"]
    while True:
        summary = call("GET", f"/lists/{list_id}").json()
        print(f"{summary['checked']}/{summary['total']} checked ({summary['status']})")
        if summary["status"] in ("done", "failed"):
            break
        time.sleep(poll_seconds)
    if summary["status"] == "failed":
        raise RuntimeError(f"list {list_id} failed")

    results, offset = [], 0
    while True:
        page = call("GET", f"/lists/{list_id}/results",
                    params={"offset": offset, "limit": 1000}).json()["results"]
        results.extend(page)
        if len(page) < 1000:
            break
        offset += 1000
    return summary, results


if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        emails = [line.strip() for line in f if line.strip()]
    try:
        summary, results = verify_list(emails)
    except MXError as e:
        sys.exit(f"Mail Exchange error: {e}")

    print("counts:", summary["counts"], "duplicates removed:", summary["duplicates_removed"])
    buckets = {}
    for row in results:
        buckets.setdefault(decide(row), []).append(row["email"])
    for action, addresses in buckets.items():
        print(action, len(addresses))
    with open("send.txt", "w") as out:
        out.write("\n".join(buckets.get("send", [])))

    call("DELETE", f"/lists/{summary['id']}")   # optional: remove the list and its results
MAILEXCHANGE_API_KEY=mx_live_xxx python mx_list.py emails.txt

Instead of polling you can pass a callback_url and let us call you when the list is done, see webhooks and callbacks. The whole flow, including CSV download and deleting a list, is in verify a list with the API.

Errors, 402 and 429

Every error response is JSON with an error field, which the helper surfaces in the exception message. The ones to plan for:

  • 429 means you hit the per-key rate limit. The helper waits 1, 2, 4 and 8 seconds and tries again, which is safe because a rate-limited request does no work and costs nothing.
  • 402 means you do not have enough credits for the request. Retrying will not help. Stop, alert someone, and top up. GET /account returns your balance if you want to check first.
  • 401 means the key is missing or wrong. 400 means the request was malformed, for example no email, or a list over 100,000 addresses.

Details and a status code table are in errors, credits and rate limits.

Questions

Is there an official Python SDK for the Mail Exchange API?

No, and none is needed. The API is plain HTTPS and JSON, so the examples on this page use only the standard library and the most common HTTP client.

How do I get an API key?

Keys are issued on request through the contact page, and they come with free test credits. Send the key as a bearer token in the Authorization header.

What should I do when /verify returns 202?

Do not send the address again. The check is already running and paid for. Read the result from /lists/{list_id}/results using the list_id in the 202 response, until the state is no longer pending.

Related