# Email Validation API Code Samples in Rust

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

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

Copy-paste Rust 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 Rust SDK](https://email-validation.org/docs/sdks/rust/) 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.

**Rust**

```rust
use email_validation::{Client, ErrorKind};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(std::env::var("EV_API_KEY")?)?;
    match client.validate("accepted@sandbox.email-validation.org").await {
        Ok(result) => println!("{} {} {}", result.status, result.reason, result.action), // valid accepted send
        Err(err) if err.kind() == ErrorKind::InsufficientCredits => println!("buy credits; nothing was charged"),
        Err(err) => println!("{} {:?}", err.code(), err.request_id()),
    }
    Ok(())
}
```

## Validate an address

**Rust**

```rust
// Cargo.toml: reqwest = { version = "0.12", features = ["json"] }, serde = { version = "1", features = ["derive"] },
//             serde_json = "1", tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use std::time::Duration;

use reqwest::StatusCode;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct ValidationResult {
    status: String,
    reason: String,
    action: String,
    credits_used: u8,
}

#[derive(Debug, Deserialize)]
struct ApiError {
    code: String,
    message: String,
    request_id: String,
}

#[derive(Debug, Deserialize)]
struct ErrorEnvelope {
    error: ApiError,
}

async fn validate(
    client: &reqwest::Client,
    key: &str,
    email: &str,
    attempts: u32,
) -> Result<ValidationResult, Box<dyn std::error::Error>> {
    let mut attempt = 0;
    loop {
        attempt += 1;
        let res = client
            .post("https://api.email-validation.org/v1/validate")
            .bearer_auth(key)
            .json(&serde_json::json!({ "email": email }))
            .send()
            .await?;
        let status = res.status();
        if status.is_success() {
            return Ok(res.json().await?);
        }
        let wait = res
            .headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u64>().ok())
            .unwrap_or(1)
            .max(1);
        let e = res.json::<ErrorEnvelope>().await?.error;
        // Never wait out a long Retry-After: key_daily_cap lasts until the next UTC day.
        let retryable = (status == StatusCode::TOO_MANY_REQUESTS || status == StatusCode::SERVICE_UNAVAILABLE)
            && e.code != "key_daily_cap"
            && wait <= 10;
        if retryable && attempt < attempts {
            tokio::time::sleep(Duration::from_secs(wait)).await;
            continue;
        }
        return Err(format!("{}: {} ({})", e.code, e.message, e.request_id).into());
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("EV_API_KEY")?;
    let client = reqwest::Client::builder().timeout(Duration::from_secs(20)).build()?;
    let r = validate(&client, &key, "accepted@sandbox.email-validation.org", 3).await?;
    // the verdict only: never print or log the address itself
    println!("{} {} {} {}", r.status, r.reason, r.action, r.credits_used);
    Ok(())
}
```

## Other calls

- Read the credit balance: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#credits)).
- Create a bulk job: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#bulk)).
- Verify a webhook: samples on [Webhooks](https://email-validation.org/docs/webhooks/#verify) and in JavaScript, TypeScript, Python, PHP, Ruby, Go, Java and C# ([all code samples](https://email-validation.org/docs/code-samples/#webhooks)).

## 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/).
