# Validate email addresses with Python

The ValidatedMails API returns structured signals about email syntax, DNS routing, and SMTP behavior so you can make consistent decisions in signups, lead forms, CRMs, and data pipelines.

Response contract:

every request returns a four-state

status

, a numeric

score

, and a

trace_id

you can use to correlate logs and support cases.

## Run the standalone Python quickstart

[Download the runnable example](/integrations/validate-email.py). Set VALIDATEDMAILS_API_KEY privately in your environment, then run `python3 validate-email.py` for a free connection check. Add `--email ADDRESS` for one validation using an address you are authorized to verify. Valid, risky, and invalid results cost one credit; unknown is free. Requests are bounded to 60 seconds and are never automatically retried.

For assistant tools, use the [MCP setup guide](/docs/mcp).

## Quickstart

Call `/validate` with a simple `GET` request using query parameters, or a `POST` request with a JSON body. Both return the same response payload.

```python
GET https://api.validatedmails.com/validate/?email=ada@acme.com&token=YOUR_API_TOKEN
```

```python
POST https://api.validatedmails.com/validate?token=YOUR_API_TOKEN
Content-Type: application/json

{
  "email": "ada@acme.com"
}
```

The response includes the four-state `status`, a boolean convenience field (`is_valid`), a numeric `score`, and a `trace_id` for correlation.

## Python example (requests)

Use `requests` and parse JSON directly. The example below shows a minimal helper for signup or ingestion flows.

```python
import os
import requests
from typing import Any, Dict

API_BASE_URL = os.getenv("VITE_API_BASE_URL", "https://api.validatedmails.com")
API_TOKEN = os.getenv("VALIDATEDMAILS_API_TOKEN", "YOUR_API_TOKEN")


def validate_email(email: str) -> Dict[str, Any]:
    response = requests.get(
        f"{API_BASE_URL}/validate/",
        params={"email": email, "token": API_TOKEN},
    )
    response.raise_for_status()
    return response.json()


def validate_email_post(email: str) -> Dict[str, Any]:
    response = requests.post(
        f"{API_BASE_URL}/validate",
        params={"token": API_TOKEN},
        json={"email": email},
    )
    response.raise_for_status()
    return response.json()


result = validate_email("ada@acme.com")
status = result["status"]
score = result["score"]
trace_id = result["trace_id"]

print("status:", status)
print("score:", score)
print("trace_id:", trace_id)

if status == "valid":
    print("Accept signup")
elif status == "invalid":
    print("Reject signup")
else:
    print("Risky or unknown: apply your review or confirmation policy")
```

Sample response payload:

```json
{
  "is_valid": true,
  "status": "valid",
  "score": 95,
  "smtp_ok": true,
  "accept_all": false,
  "disposable": false,
  "role": false,
  "free": false,
  "tag": false,
  "mx_ok": true,
  "a_ok": true,
  "trace_id": "..."
}
```

## Interpreting the response

### status + is_valid

`status` is the primary verdict output. Use it for four-state outcomes.`is_valid` is a convenience mirror for `status === "valid"`.

### score

`score` is a 0-100 confidence indicator that blends SMTP, DNS, and risk flags. Use it to rank or segment results.

## Key flags

| Field | What it means | Usage |
| --- | --- | --- |
| `accept_all` | Domain appears to accept any recipient. | Use as a risk signal when deciding follow-up steps. |
| `smtp_ok` | SMTP accepted the recipient when probed. | Use as a high-confidence routing signal. |
| `disposable` | Disposable or temporary mailbox provider. | Apply your policy for disposable addresses. |
| `role` | Role-based address (info@, support@). | Use for routing or lead-quality segmentation. |
| `free` | Consumer/free inbox provider. | Optional signal for B2B lead scoring. |
| `tag` | Plus-tagging detected. | Helpful for CRM normalization or deduplication. |
| `mx_ok` | Domain has MX records. | Combine with `a_ok` to assess routing. |
| `a_ok` | Domain has A/AAAA fallback routing. | Combine with `mx_ok` to assess routing. |

## Error handling + timeouts

- Set explicit client timeouts (connect + read) that match your application latency budget.
- For HTTP `429`, honor `Retry-After` when present. After a timeout or connection loss, the request may already have completed and been charged; review before resending. Do not retry on `status`outcomes such as `unknown`.
- Log the `trace_id` from every response to speed up support and debugging.

## Common integration patterns

### Signups (real-time)

- Accept `valid` immediately.
- Reject `invalid` to prevent hard bounces.
- Treat `unknown` as a deferred verification state (email confirmation, OTP, or review).

### Bulk checks / pipelines

- Use `POST /validate/batch` for list workloads, imports, and worker pipelines.
- Submit full batches where possible and run parallel batch workers to reach your target throughput.
- Use Bulk validation jobs for very large CSV imports and full-list processing.
- Keep `unknown` records in a separate segment and recheck later if needed.
- Use `score` plus flags (`role`, `disposable`,`accept_all`) to rank risk.
- Cache results by normalized email for a short TTL to reduce repeated probes.

## Response semantics

### Three-state outcome

`valid` means syntax and routing checks passed and SMTP accepted the recipient. `invalid` means syntax is invalid or SMTP explicitly rejected the recipient. `unknown` means routing could not be conclusively established within configured DNS or SMTP time budgets.

### Traceability

`trace_id` is the correlation key for logs, support requests, and audits. Persist it with your request metadata.
