# Email Validation API Code Samples in Python

URL: https://email-validation.org/docs/code-samples/python/
Updated: 2026-11-25

> Documentation index: https://email-validation.org/llms.txt

Copy-paste Python examples that validate one address, send the API key in the `Authorization` header, retry
`429` and `503` answers after `Retry-After` when the wait is at most 10 seconds (never `key_daily_cap`, which lasts
until the next UTC day), and report other errors with their code and request id. Each uses the free test address
`accepted@sandbox.email-validation.org`; replace it with a real address when you are ready. The same samples in other
languages: [all code samples](https://email-validation.org/docs/code-samples/).

Set your key first: `export EV_API_KEY="ev_live_…"`.

The samples call `https://api.email-validation.org`. For EU data residency, replace it with `https://api-eu.email-validation.org`, or pass the SDK's EU base URL constant;
there `/v1/validate` takes `POST` only ([EU data residency](https://email-validation.org/docs/eu-data-residency/)).

## With the official SDK

The [official Python SDK](https://email-validation.org/docs/sdks/python/) does the retries, timeouts and error mapping
for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain
HTTP samples further down call the API directly.

**Python**

```python
import os

from email_validation import EmailValidation, EmailValidationError, InsufficientCreditsError

with EmailValidation(os.environ["EV_API_KEY"]) as ev:
    try:
        result = ev.validate("accepted@sandbox.email-validation.org")
        print(result["status"], result["reason"], result["action"])  # valid accepted send
    except InsufficientCreditsError:
        print("buy credits; nothing was charged")
    except EmailValidationError as err:
        print(err.code, err.request_id)
```

## Validate an address

**Python**

```python
import os
import time

import requests  # pip install requests

API = "https://api.email-validation.org/v1/validate"
MAX_WAIT_S = 10  # never wait out a long Retry-After (key_daily_cap lasts until the next UTC day)


def validate(email: str, attempts: int = 3) -> dict:
    for attempt in range(1, attempts + 1):
        resp = requests.post(
            API,
            headers={"Authorization": f"Bearer {os.environ['EV_API_KEY']}"},
            json={"email": email},
            timeout=20,
        )
        if resp.ok:
            return resp.json()
        error = resp.json()["error"]
        wait = int(resp.headers.get("Retry-After", "1"))
        retryable = resp.status_code in (429, 503) and error["code"] != "key_daily_cap" and wait <= MAX_WAIT_S
        if retryable and attempt < attempts:
            time.sleep(wait)
            continue
        raise RuntimeError(f"{error['code']}: {error['message']} ({error['request_id']})")
    raise RuntimeError("no attempts left")


result = validate("accepted@sandbox.email-validation.org")
print(result["status"], result["reason"], result["action"], result["credits_used"])
```

## Read the credit balance

**Python**

```python
import os

import requests  # pip install requests

resp = requests.get(
    "https://api.email-validation.org/v1/credits",
    headers={"Authorization": f"Bearer {os.environ['EV_API_KEY']}"},
    timeout=10,
)
resp.raise_for_status()
credits = resp.json()
print("Balance:", credits["balance"])
for lot in credits["lots"]:
    print(lot["remaining"], "credits expire on", lot["expires_at"][:10])
```

## Create a bulk job

**Python**

```python
import os

import requests  # pip install requests

with open("customers.csv", "rb") as f:
    resp = requests.post(
        "https://api.email-validation.org/v1/bulk",
        params={"column": "email", "has_header": "true"},
        headers={"Authorization": f"Bearer {os.environ['EV_API_KEY']}", "Content-Type": "text/csv"},
        data=f.read(),
        timeout=120,
    )
job = resp.json()
if not resp.ok:
    raise RuntimeError(f"{job['error']['code']}: {job['error']['message']}")
print(job["id"], job["status"])
```

## Verify a webhook

**Python**

```python
import base64
import hashlib
import hmac
import json
import time


def verify_webhook(raw_body: bytes, headers, secret: str, tolerance: int = 300) -> dict:
    """headers: any case-insensitive mapping, e.g. request.headers in Flask or Django."""
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not (msg_id and timestamp and signatures):
        raise ValueError("missing webhook headers")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance:
        raise ValueError("timestamp outside tolerance")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()
    for entry in signatures.split(" "):
        version, _, sig = entry.partition(",")
        if version != "v1" or not sig:
            continue
        try:
            given = base64.b64decode(sig)
        except ValueError:
            continue
        if hmac.compare_digest(given, expected):
            return json.loads(raw_body)
    raise ValueError("no valid signature")


# Flask: event = verify_webhook(request.get_data(), request.headers, os.environ["EV_WEBHOOK_SECRET"])
```

## Notes

- Use `POST` with a JSON body; it keeps addresses out of URLs and logs.
- Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
- A `200` answer with the status `unknown` is a normal, free result, not an error.
- Every endpoint, field and error: the [API reference](https://email-validation.org/docs/api-reference/).
