Metadata-Version: 2.5
Name: email-validation-sdk
Version: 1.1.0
Summary: Official Python client for the email-validation.org email validation API.
Project-URL: Homepage, https://email-validation.org/docs/sdks/python/
Project-URL: Documentation, https://email-validation.org/docs/
Author-email: "email-validation.org" <support@email-validation.org>
License-Expression: MIT
License-File: LICENSE
Keywords: api,email,email validation,email verification,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Communications :: Email
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# email-validation.org Python SDK

Official Python client for the [email-validation.org](https://email-validation.org) API: validate single addresses,
read credits and usage, run bulk jobs (upload, wait, stream or download the results) and verify webhook signatures.
Synchronous and asynchronous clients, typed results (`TypedDict`) and typed errors. Python 3.10 or later; one
dependency, [httpx](https://www.python-httpx.org/).

Documentation: https://email-validation.org/docs/sdks/python/

## Install

```bash
pip install email-validation-sdk
```

The package is imported as `email_validation`.

## Quick start

```python
import os

from email_validation import EmailValidation

with EmailValidation(os.environ["EV_API_KEY"]) as ev:
    result = ev.validate("accepted@sandbox.email-validation.org")  # a free test address
    print(result["status"], result["reason"], result["action"])  # valid accepted send
```

`status` is one of five: `valid`, `invalid`, `catch_all`, `unknown` or `disposable` (spam traps and frequent
complainers are `valid` with the action `remove`); `unknown` results never cost a credit.

## Client options

```python
import os

from email_validation import EU_BASE_URL, EmailValidation

ev = EmailValidation(
    os.environ["EV_API_KEY"],  # required, no spaces
    base_url=EU_BASE_URL,  # default https://api.email-validation.org; EU_BASE_URL validates and stores in the EU
    timeout=30.0,  # seconds per attempt (see below)
    max_retries=2,  # retries after 429 / 503 answers (and, for reads only, after no answer)
    max_retry_wait=10.0,  # a longer Retry-After is raised to you instead of waited out
)
```

- `timeout` bounds each attempt of a JSON call as a whole (connect, send, the full answer; an answer that has fully
  arrived is never thrown away). For transfers (a file upload, `bulk.results`, `bulk.results_stream`,
  `bulk.download`) it is an idle timeout: the attempt fails only when no byte was sent or received for that long, so
  a large but progressing transfer is never cut.
- Bytes still in the send buffers do not count as progress, so a request body adds its drain time,
  `min(size, 4 MiB) / 128 KiB/s` (at most 32 s): an upload's writes and its wait for the answer may take `timeout`
  plus that, and so may the whole attempt of a JSON call with a large body (`bulk.create(emails=…)`).
- Every method takes `request_timeout=` (seconds) to replace `timeout` for that one call, e.g.
  `ev.credits(request_timeout=5)`.
- `transport=` replaces the HTTP stack (see "Bring your own HTTP client"); `sleep=` and `clock=` are for tests.

## Validate an address

```python
result = ev.validate(
    "accepted@sandbox.email-validation.org",
    ip_address="203.0.113.7",  # the signer's IP, optional
    timeout=10,  # seconds the service may spend on the check, 5-15 (keep the client timeout a few seconds above)
    fresh=True,  # check again even when the address was checked in the last 12 months
)
```

Results are plain dictionaries described by `TypedDict` types. A newer API may send a reason or provider this
version does not know: it arrives as the raw string (`is_reason()` tells you).

## Async

```python
import asyncio
import os

from email_validation import AsyncEmailValidation


async def main() -> None:
    async with AsyncEmailValidation(os.environ["EV_API_KEY"]) as ev:
        results = await asyncio.gather(
            ev.validate("accepted@sandbox.email-validation.org"),
            ev.validate("catch_all@sandbox.email-validation.org"),
        )
        for r in results:
            print(r["email"], r["status"])


asyncio.run(main())
```

`AsyncEmailValidation` has the same methods and options. Cancelling the task raises `asyncio.CancelledError` at
once, during a request, a retry wait, a `bulk.wait` poll wait or a stream read; nothing is retried after it.

## Credits, usage and status

```python
credits = ev.credits()  # {"balance": ..., "debt": ..., "pending": ..., "lots": [...]}
usage = ev.usage(from_date="2026-11-01", to_date="2026-11-05", group_by="day")  # or group_by="key"
status = ev.status()  # {"status": "operational", ...}
```

## Bulk jobs

```python
import io
import pathlib

job = ev.bulk.create(emails=["accepted@sandbox.email-validation.org", "catch_all@sandbox.email-validation.org"])
job = ev.bulk.create(file=pathlib.Path("customers.csv"), column="email", has_header=True)  # a path
job = ev.bulk.create(file=io.BytesIO(b"accepted@sandbox.email-validation.org\n"), content_type="text/plain")  # a stream
job = ev.bulk.create(file="email\naccepted@sandbox.email-validation.org\n")  # a str is the content, never a path

job = ev.bulk.create(emails=["accepted@sandbox.email-validation.org"], start=False)
ev.bulk.start(job["id"])  # a job created with start=False waits in "ready": start it before wait()
job = ev.bulk.wait(job["id"], on_progress=lambda j: print(j["status"], j["processed"]))

if job["status"] == "completed":
    csv_bytes = ev.bulk.results(job["id"], filter=["valid", "catch_all"])  # the whole file in memory
    with ev.bulk.results_stream(job["id"]) as chunks:  # chunk by chunk
        for chunk in chunks:
            print(len(chunk))
    size = ev.bulk.download(job["id"], "results.csv")  # into a file; a second call resumes a partial one
elif job["status"] == "ready":
    print("could not start:", job["error_code"])  # e.g. insufficient_credits: buy credits, then ev.bulk.start()
```

- `file=` takes bytes, text, a path (`os.PathLike`) or a binary file object; it is read once and sent with a
  `Content-Length`. Pass exactly one of `emails=` and `file=`.
- `wait()` polls every `interval` seconds (default 5, at least 1) until the job is `completed`, `failed`,
  `cancelled` or `expired`, or is still `ready` with an `error_code` (it could not start and will not move on by
  itself). `timeout=` gives up earlier with `APIConnectionError` (`code` `timeout`).
- `filter` is `"all"`, one status or a non-empty list (tuple, set or other iterable) of statuses; anything else
  (`[]`, `"all"` in a list, a retired name such as `risky`) raises `ValueError` before any request.
- `range="bytes=…"` (on `results` and `results_stream`) fetches a part of the file: only `filter="all"` (or one status
  with `escape_formulas=False`) with the original columns can be fetched in parts; another shape answered whole
  raises `InvalidRequestError` and the body is not read.
- `download(job_id, path, resume=True)` appends only the missing end to a partial file (`Range: bytes=<size>-`),
  returns the file size, and leaves a file that is already complete unchanged. A failure while writing keeps the
  partial file for the next call.

## Handle errors

```python
from email_validation import EmailValidationError, InsufficientCreditsError, RateLimitError

try:
    ev.validate("accepted@sandbox.email-validation.org")
except InsufficientCreditsError:
    ...  # buy credits; nothing was charged
except RateLimitError as err:
    print("retry in", err.retry_after, "seconds")
except EmailValidationError as err:
    print(err.code, err.status, err.request_id)
    print(err)  # message (Kind, status …, code …, request id …)
```

Every error has `status` (0 when no answer arrived), `code`, `message`, `request_id`, `retry_after` and `headers`.
Branch on the class or on `code`, never on the message. Classes: `InvalidRequestError` (400, 411, 413, other 4xx, a
malformed job id, a refused range), `AuthenticationError` (401), `InsufficientCreditsError` (402),
`PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429),
`ServiceUnavailableError` (503), `ServerError` (500 and other statuses, a redirect included) and
`APIConnectionError` (no answer: `connection_error` or `timeout`). An answer that is not JSON is an
`EmailValidationError` with `code` `unexpected_response`. Bad arguments raise `ValueError` or `TypeError`.

## Retries, timeouts and cancellation

- `429` and `503` answers are never charged, so they are retried for every call (up to `max_retries`), waiting the
  `Retry-After` seconds or, without one, a short backoff with jitter (0.25-0.5 s, then 0.5-1 s, …). A
  `key_daily_cap` (it resets the next day) and a wait longer than `max_retry_wait` are raised at once.
- No answer (a network failure or a timeout) is retried for reads (GET) only: a check, an upload, a start or a
  cancel that reached the service may already have been applied or charged, so it is never sent twice. A results
  stream or download is never retried once a byte reached you. Nothing else is retried (400-428, 500, 502, 504).
- Timeouts: see "Client options" (`timeout` per attempt, idle for transfers, `request_timeout` per call).
- Cancellation: the async client stops at once on task cancellation (`asyncio.CancelledError`); the sync client has
  none, use `request_timeout`.

## Verify webhooks

```python
import os

from email_validation import WebhookVerificationError, verify_webhook
from flask import Flask, request

app = Flask(__name__)


@app.post("/webhooks/email-validation")
def webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers, os.environ["EV_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return "invalid signature", 400
    if event["type"] == "bulk.completed":
        print("job done", event["data"]["job_id"])
    return "", 204
```

Pass the raw body (bytes or str, before any JSON parsing) and the headers: a `dict` (string or list values) or any
object with `items()`, such as Flask's, Django's or Starlette's headers; names match in any case and repeated values
are joined. `tolerance=` (default `DEFAULT_WEBHOOK_TOLERANCE`, 300 s) bounds the timestamp's age. Deduplicate on the
`webhook-id` header (retries reuse it), answer `2xx` quickly, and expect `webhook.test` events from **Send test** in
the dashboard. `sign_webhook()` makes a valid signature for local tests.

## Constants

```python
from email_validation import (
    DEFAULT_BASE_URL,
    DEFAULT_WEBHOOK_TOLERANCE,
    ERROR_CODES,
    EU_BASE_URL,
    REASONS,
    REASONS_BY_STATUS,
    STATUSES,
    TERMINAL_BULK_JOB_STATUSES,
    is_reason,
    is_status,
    sandbox_address,
)

print(STATUSES)  # ('valid', 'invalid', 'catch_all', 'unknown', 'disposable')
print(sandbox_address("no_mailbox"))  # no_mailbox@sandbox.email-validation.org, free to check
print(is_status("risky"), is_reason("accepted"))  # False True
```

Also `ACTIONS`, `SMTP_PROVIDERS`, `BULK_JOB_STATUSES`, `WEBHOOK_EVENTS`, `SANDBOX_DOMAIN` and the types `Status`,
`Reason`, `Action`, `BulkJobStatus`.

## Bring your own HTTP client

```python
import os

import httpx

from email_validation import EmailValidation, HttpxTransport

client = httpx.Client(proxy="http://proxy.internal:3128")
ev = EmailValidation(os.environ["EV_API_KEY"], transport=HttpxTransport(client))  # you close your client
```

`HttpxTransport(client)` / `AsyncHttpxTransport(client)` wrap your configured `httpx.Client` / `httpx.AsyncClient`
(proxies, TLS); redirects are never followed, even when your client was created with `follow_redirects=True`. Any
object with `send(request) -> HttpResponse` and `close()` also works (async: `send` and `aclose`), for example in
tests; an optional `stream(request, chunk_size) -> HttpStream` lets `results_stream` and `download` read in chunks.
With `stream()`, the SDK bounds a stream's wait for the answer and for each read itself, whatever the transport does;
the async client also bounds every JSON call. Only your transport's own timeouts bound a sync transport's `send()`
(its JSON calls), and `results_stream` and `download` through a transport without `stream()`, which read the whole
body in one `send()` call: give your transport timeouts.

## Privacy

The API key travels only in the `Authorization` header: never in a URL, a log line, an error message or the `repr()`
of the client, its configuration, a request or a response (those also hide the checked address). The SDK writes
nothing to stdout or stderr and sends no telemetry.

## Licence

MIT, see LICENSE.
