Official SDK
Python SDK
The official Python SDK offers a synchronous and an asynchronous client with the same methods, typed results and typed errors. It needs Python 3.11 or later (tested on Python 3.14 and 3.15) and uses httpx for HTTP. Python 3.10 is past its end of life and not supported: version 1.1.0 still installs there but is not tested on it, and later versions need 3.11.
- PyPI package
email-validation-sdk- Registry
- PyPI
- State
- Published Version 1.1.0
Published on PyPI: email-validation-sdk, version 1.1.0.
Install
python3 --version (on Windows: py --version) shows your Python: it must be 3.11 or later. The python3 that comes with macOS is older, and pip there finds no matching version: install Python from python.org or Homebrew first. Then, in a terminal (on Windows: PowerShell), make a project folder with its own virtual environment and add the SDK to it:
macOS / Linux
mkdir ev-quickstart
cd ev-quickstart
python3 -m venv .venv
.venv/bin/python -m pip install email-validation-sdkPowerShell
mkdir ev-quickstart
cd ev-quickstart
py -m venv .venv
.venv\Scripts\python -m pip install email-validation-sdkThe package is imported as email_validation.
Set your API key
Create a key under API keys (quickstart step 1). The code below reads it from the EV_API_KEY environment variable. In the same terminal, run the line for your system, paste the key and press Enter (the key does not show):
macOS / Linux
# Paste the key, then press Enter.
read -rs EV_API_KEY && export EV_API_KEYPowerShell
# Windows PowerShell 5.1 and PowerShell 7. This window only. Paste the key, then press Enter:
$env:EV_API_KEY = [Net.NetworkCredential]::new('', (Read-Host -AsSecureString)).PasswordOptional: to keep the key for windows you open later, run setx EV_API_KEY $env:EV_API_KEY once after the line above. It saves the key in your Windows user environment. To remove it again, run [Environment]::SetEnvironmentVariable('EV_API_KEY', $null, 'User') and open a new window.
In Command Prompt (cmd.exe), run set /p EV_API_KEY= instead and paste the key: Command Prompt shows it as you paste, so run cls afterwards to clear the screen. The key stays set until you close that window.
Validate an address
Save this as main.py in the folder:
import os
from email_validation import EmailValidation
with EmailValidation(os.environ["EV_API_KEY"]) as ev:
result = ev.validate("accepted@sandbox.email-validation.org")
print(result["status"], result["reason"], result["action"]) # valid accepted sendThen run it in the same terminal:
macOS / Linux
.venv/bin/python main.pyPowerShell
.venv\Scripts\python main.pyOptions: ip_address, timeout (seconds the check may take, 5–15) and fresh. fresh=True checks the address again even when it was checked in the last 12 months (see repeat checks). Results are plain dictionaries described by TypedDict types, so editors and type checkers know every field.
The with block closes the client at its end. The snippets below use one client, ev, that stays open: create it once and close it when your program ends.
import os
from email_validation import EmailValidation
ev = EmailValidation(os.environ["EV_API_KEY"])
# ... the snippets below ...
ev.close()EU data residency
To check addresses and store their results in the EU, point the client at the EU endpoint, https://api-eu.email-validation.org, with EU_BASE_URL:
from email_validation import EU_BASE_URL, EmailValidation
ev = EmailValidation(os.environ["EV_API_KEY"], base_url=EU_BASE_URL)Everything else stays the same; on the EU endpoint a check is always sent as a POST. See EU data residency.
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())Keep concurrency within your rate limit; for long lists use a bulk job. Cancelling the task raises asyncio.CancelledError at once (during a request, a retry wait, a bulk.wait poll or, from version 1.1.0, a stream read), and nothing is retried after it.
In an aiohttp or Tornado app
Check the address in your server's sign-up handler. Keep the API key on your server: a web page that checks as people type uses a browser key and the form guard instead. The handler below blocks only what is clearly wrong and lets everyone else through, as the sign-up guide explains. Save it as screen.py:
from email_validation import AsyncEmailValidation, EmailValidationError
async def screen_signup_email(ev: AsyncEmailValidation, email: str) -> dict:
"""{"ok": bool, ...} for your sign-up handler. Never blocks on our errors."""
try:
r = await ev.validate(email, timeout=6, request_timeout=10)
except EmailValidationError: # 402, 429, 503, a timeout or no answer: treat like unknown
return {"ok": True, "recheck": True}
if r["status"] == "invalid":
hint = f"Did you mean {r['did_you_mean']}?" if r["did_you_mean"] else "Please check this email address."
return {"ok": False, "message": hint}
if r["status"] == "disposable" or r["disposable"] is True:
return {"ok": False, "message": "Please use a permanent email address."}
if r["status"] == "unknown": # no verdict yet (free): accept, check later
return {"ok": True, "recheck": True}
return {"ok": True, "flag": r["action"] != "send"} # catch_all, or valid but not "send": accept and flag| Step | aiohttp | Tornado |
|---|---|---|
| One client for the app | Opened in a cleanup context, closed on shutdown | Opened in main(), inside the running event loop |
| Handed to the handler | app[EV], a web.AppKey (aiohttp 3.9 or later) | initialize(), from the route's third element |
| JSON body | await request.json() | json.loads(self.request.body) (Tornado does not parse it) |
max_retries=0 and request_timeout=10 keep the form fast: a sign-up never waits out a retry. timeout=6 is the check's own budget; a check that runs out of time is unknown and free.
aiohttp (app.py, beside screen.py):
import os
from aiohttp import web
from email_validation import AsyncEmailValidation
from screen import screen_signup_email
EV = web.AppKey("ev", AsyncEmailValidation)
async def email_validation(app: web.Application):
async with AsyncEmailValidation(os.environ["EV_API_KEY"], max_retries=0) as ev:
app[EV] = ev
yield # the app runs here; the client closes on shutdown
async def signup(request: web.Request) -> web.Response:
try:
data = await request.json()
except ValueError:
raise web.HTTPBadRequest()
email = data.get("email") if isinstance(data, dict) else None
if not isinstance(email, str) or not email.strip():
raise web.HTTPBadRequest()
verdict = await screen_signup_email(request.app[EV], email.strip())
# if verdict["ok"]: create the account here
return web.json_response(verdict, status=200 if verdict["ok"] else 422)
app = web.Application()
app.cleanup_ctx.append(email_validation)
app.router.add_post("/signup", signup)
if __name__ == "__main__":
web.run_app(app)Tornado (app.py, beside screen.py):
import asyncio
import json
import os
import tornado.web
from email_validation import AsyncEmailValidation
from screen import screen_signup_email
class SignupHandler(tornado.web.RequestHandler):
def initialize(self, ev: AsyncEmailValidation) -> None:
self.ev = ev
async def post(self) -> None:
try:
data = json.loads(self.request.body)
except ValueError:
raise tornado.web.HTTPError(400)
email = data.get("email") if isinstance(data, dict) else None
if not isinstance(email, str) or not email.strip():
raise tornado.web.HTTPError(400)
verdict = await screen_signup_email(self.ev, email.strip())
# if verdict["ok"]: create the account here
self.set_status(200 if verdict["ok"] else 422)
self.write(verdict)
async def main() -> None:
async with AsyncEmailValidation(os.environ["EV_API_KEY"], max_retries=0) as ev:
app = tornado.web.Application([(r"/signup", SignupHandler, dict(ev=ev))])
app.listen(8888)
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())Every request to /signup runs a check, and a billable check costs a credit: add a bot check and a rate limit to the route, as for any sign-up endpoint.
Handle errors
from email_validation import EmailValidationError, InsufficientCreditsError, RateLimitError
address = "accepted@sandbox.email-validation.org"
try:
ev.validate(address)
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)Every error from a call to the API is an EmailValidationError with status (0 when no answer arrived), code, request_id and retry_after. Classes: InvalidRequestError, AuthenticationError, InsufficientCreditsError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, ServiceUnavailableError, ServerError and APIConnectionError. An argument of the wrong shape, such as a bad results filter, raises ValueError or TypeError before anything is sent, and a malformed job id is an InvalidRequestError with status 0, also unsent. The API checks values, such as an empty address or a validation timeout outside 5–15 seconds, and answers 400 invalid_request, which costs nothing. verify_webhook raises its own WebhookVerificationError, which has none of these fields (verify webhooks).
Retries and timeouts
ev = EmailValidation(
os.environ["EV_API_KEY"],
timeout=30.0, # seconds per attempt
max_retries=2, # after 429 / 503 answers
max_retry_wait=10.0, # longer Retry-After values are raised to you instead of waited out
)
credits = ev.credits(request_timeout=5) # this call only (from version 1.1.0)429 and 503 answers are retried with backoff, honoring Retry-After. A daily key cap is never retried, and a validation, upload, start or cancel is never retried after a network failure or a timeout, because it may already have been charged or applied (reads are).
From version 1.1.0, timeout bounds each attempt of a call that answers JSON as a whole: connecting, sending and reading the full answer (version 1.0 applies it to each network read and write instead). For transfers (a file upload, bulk.results, bulk.results_stream and bulk.download) it is an idle timeout: the attempt fails only when no byte was sent or received for that long, so a large file that keeps moving is never cut. Bytes still waiting in the send buffers do not count as moving, so an upload (and a JSON call with a large body) may also take the time to send its body, at most 4 MiB of it, at 128 KiB/s (up to 32 s more). 1.1.0 also adds request_timeout= (seconds) to every method, which replaces timeout for that one call, each poll of bulk.wait included. Both raise APIConnectionError with code timeout.
A bulk.create that ends in a timeout or connection_error, or is cancelled (asyncio.CancelledError, async client), may still have created the job: the service can receive the whole list after the SDK stopped waiting, and unless you passed start=False that job may have started and charged its eligible checks. The API has no job list and no idempotency key, so before you upload the list again, look for the job under Bulk lists in the dashboard (jobs created through the API are listed there too, as "Untitled list" with their upload time). A webhook cannot tell you whether the job was created: a job created through the API sends bulk.completed / bulk.failed only to the endpoint you passed as webhook_endpoint_id, and only when the job ends.
Credits, usage and status
credits = ev.credits() # {"balance": ..., "debt": ..., "pending": ..., "lots": [...]}
# the last 90 days by default; pass from_date / to_date as YYYY-MM-DD for another range
usage = ev.usage(group_by="day")
status = ev.status()Bulk jobs
Bulk calls need a key with the Bulk lists permission (the bulk scope). New keys get only validate and account:read, so turn it on for the key in the dashboard first; without it, every bulk call fails with 403 forbidden (scopes).
Each block below creates exactly one job and follows that job's id: copy one of them, not both (every create is a new job, and a job that starts uses credits for its eligible checks). From a list:
job = ev.bulk.create(emails=["accepted@sandbox.email-validation.org", "catch_all@sandbox.email-validation.org"])
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
size = ev.bulk.download(job["id"], f"results-{job['id']}.csv") # 1.1.0: into a file; the next call resumes a failed one
elif job["status"] == "ready":
print("could not start:", job["error_code"]) # e.g. insufficient_credits: buy credits, then ev.bulk.start(job["id"])Or from a CSV file, then fetch the results as above:
import pathlib
# a path or a file object needs version 1.1.0; with 1.0 pass the bytes: pathlib.Path("customers.csv").read_bytes()
job = ev.bulk.create(file=pathlib.Path("customers.csv"), column="email", has_header=True)
job = ev.bulk.wait(job["id"])
print(job["status"])wait() returns when the job is completed, failed, cancelled or expired, or when it is still ready with an error_code: it could not start, for example insufficient_credits, and will not continue on its own. Pass timeout= (seconds) to give up earlier.
Also: ev.bulk.get(job_id), ev.bulk.start(job_id) for jobs created with start=False (once the job is ready, not while it is still analyzing; then wait()), and ev.bulk.cancel(job_id). file= takes bytes or text (from version 1.1.0 also a path or a binary file object), sent with a Content-Length.
results returns the whole file as bytes. From version 1.1.0, ev.bulk.download(job_id, path) streams the file to disk without holding it in memory and returns the file size.
In 1.1.0, with resume=True (the default), download continues any non-empty file already at path: it asks only for the rest of the file (Range: bytes=<size>-) and appends it, and a file that is already complete is left as it is. Give each job its own path (for example results-<job id>.csv). A failure keeps what was written, so the next call resumes. Resuming works for filter="all" (or a single status of valid, invalid or unknown with escape_formulas=False) and the original columns. In 1.1.0, any other shape with resume=True and a non-empty file already at path raises ValueError before anything is sent: pass resume=False or write to a new file. A single catch_all or disposable status with formula escaping off passes that check in 1.1.0 but cannot resume either: the request is sent, the call raises InvalidRequestError and the file is left as it was. resume=False downloads the whole file again.
From the next release, download writes into <path>.<job id>.<shape>.part beside path (e.g. results.csv.job_….all-original-escaped.part) and moves it onto path once it is complete: a file already at path is replaced only then, and left as it was if the call fails. A failure keeps the partial file: with resume=True the next call fetches only the rest of it. It continues that job's own partial file for the same filter, columns and escape_formulas, never the file at path, so the same path can be reused across jobs, and a second call after success downloads the file again. A shape that cannot resume then downloads from byte 0 instead of raising. Run one download per destination at a time.
To process the rows yourself, read the file in chunks (also 1.1.0):
with ev.bulk.results_stream(job["id"]) as chunks:
for chunk in chunks:
handle(chunk) # bytesOnly the full file (filter="all", or a single status of valid, invalid or unknown with escape_formulas=False, original columns) can be fetched in parts (range="bytes=…" on results, or a resumed download); other shapes raise InvalidRequestError when given a range (for download, see above).
Verify webhooks
This example uses Flask: add it to the project with .venv/bin/python -m pip install flask (on Windows: .venv\Scripts\python -m pip install flask).
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 "", 204event["type"] can also be webhook.test, sent when you press Send test in the dashboard: answer it with a 2xx like any other event. sign_webhook(msg_id, timestamp, payload, secret) (timestamp in Unix seconds) returns a valid webhook-signature value for local tests.
Constants
from email_validation import REASONS_BY_STATUS, STATUSES, is_status, sandbox_address
print(STATUSES) # ('valid', 'invalid', 'catch_all', 'unknown', 'disposable')
print(REASONS_BY_STATUS["invalid"]) # the reasons an invalid address can have
print(sandbox_address("no_mailbox")) # no_mailbox@sandbox.email-validation.org, free to check
print(is_status("valid"), is_status("accepted")) # True False (accepted is a reason)STATUSES, REASONS, REASONS_BY_STATUS, ACTIONS, SMTP_PROVIDERS, BULK_JOB_STATUSES, TERMINAL_BULK_JOB_STATUSES, ERROR_CODES, WEBHOOK_EVENTS, is_status(value), is_reason(value) and sandbox_address(reason) mirror the API's vocabulary; Status, Reason, Action and BulkJobStatus are their types. DEFAULT_BASE_URL, EU_BASE_URL, SANDBOX_DOMAIN and DEFAULT_WEBHOOK_TOLERANCE hold the defaults. See the statuses and reasons and test addresses pages.
Bring your own HTTP client
Pass transport= to use a configured httpx.Client (proxies, custom TLS) through HttpxTransport(client), or any object with send(request) and close() methods, for example in tests.
The names and logos of other companies and projects belong to their owners; showing them here does not mean they endorse or partner with us.