Skip to main content

email-validation.org Python SDK

Official Python client for the 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.

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

Install

pip install email-validation-sdk

The package is imported as email_validation.

Quick start

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

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

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

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

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

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

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

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

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

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.

Metadata

Release files for email-validation-sdk 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for email-validation-sdk 1.1.0
File Size Uploaded Provenance Actions
email_validation_sdk-1.1.0.tar.gz 31.0 kB Without provenance Details for email_validation_sdk-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for email-validation-sdk 1.1.0
File Interpreter ABI Platform Actions
email_validation_sdk-1.1.0-py3-none-any.whl Python 3 none any Details for email_validation_sdk-1.1.0-py3-none-any.whl

Total release size: 68.8 kB

Release files / email_validation_sdk-1.1.0.tar.gz

Download URL email_validation_sdk-1.1.0.tar.gz
Size 31.0 kB
Tags Source
SHA-256 checksum
How to use checksums
ce13327c9c5db2e81675e0af16519665c306c91751016c7dbd714294907ca432
BLAKE2b-256 checksum
How to use checksums
5d8d41dccc058e7f6475d04c890c536d1c729e02a5679ebf7be66a5ec5061213
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / email_validation_sdk-1.1.0-py3-none-any.whl

Download URL email_validation_sdk-1.1.0-py3-none-any.whl
Size 37.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fed9456b25af76b3f6e66a971900435c01bc2bec9f9269880302e5093a2d03b2
BLAKE2b-256 checksum
How to use checksums
1277ffd8b15d538c0097caf4f44e5a6b84d7907d28559acaf981a6345f9fa044
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Security for email-validation-sdk 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page