# Elixir SDK

URL: https://email-validation.org/docs/sdks/elixir/
Updated: 2026-11-27

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

The official Elixir SDK returns result structs, one error struct to match on and retries the answers that are never
charged. It needs Elixir 1.18 or later and has no dependencies: only Elixir and OTP (`:ssl`, `:public_key`,
`:crypto` and Elixir's built-in `JSON`).

**Not published yet.** The Hex package `email_validation_sdk` is not on Hex yet, so there is
no install command to run today. The SDK is complete and tested and coming soon to its registry. Until then, use
the [code samples](https://email-validation.org/docs/code-samples/), which call the API directly, for example
[curl](https://email-validation.org/docs/code-samples/curl/).

## Install

The install command appears here once `email_validation_sdk` is on Hex (coming soon).

The modules live under `EmailValidation`.

## Validate an address

```elixir
client = EmailValidation.Client.new(api_key: System.fetch_env!("EV_API_KEY"))

{:ok, result} = EmailValidation.validate(client, "accepted@sandbox.email-validation.org")
IO.puts("#{result.status} #{result.reason} #{result.action}") # valid accepted send
```

Build the client once and share it: it is an immutable struct, safe to use from any process, and its connections are
kept alive. Options: `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](https://email-validation.org/docs/api/validate/#repeat-checks)). Every call returns `{:ok, value}` or
`{:error, %EmailValidation.Error{}}`, and has a `!` variant that raises instead. Results are structs with the API's
field names; `JSON.encode!/1` gives back the API's JSON.

## EU data residency

To have checks validated and their results stored in the EU, point the client at the EU endpoint, `https://api-eu.email-validation.org`, with
`EmailValidation.eu_base_url()`:

```elixir
client =
  EmailValidation.Client.new(api_key: System.fetch_env!("EV_API_KEY"), base_url: EmailValidation.eu_base_url())
```

Everything else stays the same; on the EU endpoint a check is always sent as a `POST`. See
[EU data residency](https://email-validation.org/docs/eu-data-residency/).

## Async

Elixir has no separate async surface: every call blocks its own process, and the client can be shared by as many
processes as you like. Run checks concurrently with `Task.async_stream/3`, within your
[rate limit](https://email-validation.org/docs/rate-limits/), or use a bulk job for lists:

```elixir
addresses = ["accepted@sandbox.email-validation.org", "catch_all@sandbox.email-validation.org"]

addresses
|> Task.async_stream(&EmailValidation.validate(client, &1), max_concurrency: 4, timeout: 60_000)
|> Enum.each(fn {:ok, {:ok, result}} -> IO.puts("#{result.email}: #{result.status}") end)
```

## Handle errors

```elixir
case EmailValidation.validate(client, address) do
  {:ok, result} -> IO.puts(result.status)
  {:error, %EmailValidation.Error{kind: :insufficient_credits}} -> IO.puts("buy credits; nothing was charged")
  {:error, %EmailValidation.Error{kind: :rate_limit} = error} -> IO.puts("retry in #{error.retry_after} seconds")
  {:error, %EmailValidation.Error{} = error} -> IO.puts("#{error.code} #{error.status} #{error.request_id}")
end
```

Every error is an `%EmailValidation.Error{}` exception with `kind`, `status` (0 when no answer arrived), `code`,
`message`, `request_id` and `retry_after`. Kinds: `:invalid_request`, `:authentication`, `:insufficient_credits`,
`:permission_denied`, `:not_found`, `:conflict`, `:rate_limit`, `:service_unavailable`, `:server`, `:connection` and
`:email_validation` (a 2xx answer that is not JSON). Wrong arguments raise `ArgumentError` before any request is sent.

## Retries and timeouts

```elixir
client =
  EmailValidation.Client.new(
    api_key: System.fetch_env!("EV_API_KEY"),
    timeout: 30_000, # milliseconds per attempt
    max_retries: 2, # after 429 / 503 answers
    max_retry_wait: 10_000 # longer Retry-After values are returned to you instead of waited out
  )

# every call takes request_timeout: for that one call
{:ok, credits} = EmailValidation.credits(client, request_timeout: 5_000)
```

`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 sent again after a network failure, because it may already have been
charged or applied.

`timeout` bounds each attempt of a JSON call as a whole. Transfers (a file upload, results and downloads) use it as
an idle timeout: the attempt fails only when no byte moves for that long, so a slow but progressing 100 MB file is
never cut, and the timer never runs while your code handles a streamed chunk. An answer cut short by a closed
connection is a `:connection` error `connection_error`, never a complete result. To cancel a call, stop the process
that makes it (`Task.shutdown/2`): the request stops at once and nothing more is sent.

A `Bulk.create` that ends in a `timeout` or `connection_error` (or is cancelled) 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 runs
and is charged. The API has no job list and no idempotency key, so before you upload the list again, look for the job
under [Bulk lists](https://email-validation.org/app/bulk/) in the dashboard (jobs created through the API are listed there too, as "Untitled
list" with their upload time). A webhook cannot tell you: 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

```elixir
{:ok, credits} = EmailValidation.credits(client) # balance, debt, pending, lots
# the last 90 days by default; pass from: / to: as YYYY-MM-DD (or a Date) for another range
{:ok, usage} = EmailValidation.usage(client, group_by: "day")
{:ok, status} = EmailValidation.status(client)
```

## Bulk jobs

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). From a list:

```elixir
alias EmailValidation.Bulk

{:ok, job} = Bulk.create(client, emails: ["accepted@sandbox.email-validation.org", "catch_all@sandbox.email-validation.org"])

{:ok, job} = Bulk.wait(client, job.id, on_progress: fn j -> IO.puts("#{j.status} #{j.processed}") end)

cond do
  job.status == "completed" ->
    {:ok, csv} = Bulk.results(client, job.id, filter: ["valid", "catch_all"])
    {:ok, bytes} = Bulk.download(client, job.id, "results.csv") # to a file; a failed call resumes
    IO.puts("#{byte_size(csv)} bytes filtered, #{bytes} in results.csv")

  EmailValidation.BulkJob.stuck?(job) ->
    # e.g. insufficient_credits: buy credits, then Bulk.start(client, job.id)
    IO.puts("could not start: #{job.error_code}")

  true ->
    IO.puts("job #{job.status}")
end
```

Or from a CSV file (up to 100 MB: its content, `{:path, path}` or a stream of binaries), then fetch the
results as above:

```elixir
alias EmailValidation.Bulk

{:ok, job} = Bulk.create(client, file: {:path, "customers.csv"}, column: "email", has_header: true)
{:ok, job} = Bulk.wait(client, job.id)
IO.puts("job #{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 and does not move on by itself. Pass `timeout:` (milliseconds) to give up earlier.
Also: `Bulk.get`, `Bulk.start` for jobs created with `start: false` (call it before `wait`), `Bulk.cancel`, and
`Bulk.results_stream`, a lazy stream of chunks for large files.

`Bulk.download(client, job_id, path)` writes the results into a file without holding them in memory and returns the
file's length. It writes into a partial file beside `path`, `<path>.<job id>.<filter>-<columns>-<escaping>.part`
(e.g. `results.csv.job_7Hq2LmX9cV4bN8tR1zK6wD.all-original-escaped.part`), and moves it onto `path` once it is
complete: a file already at `path` is replaced only then, and a failed or cancelled call leaves it as it was. The file
at `path` is never read or resumed, so you can reuse one path for several jobs, and a second call after a success
downloads the file again. With `resume: true` (the default), the partial file of this job and shape left by a failed
call is continued: only the missing end is fetched and appended. Resuming works for `filter: "all"` (or a single status of `valid`, `invalid` or `unknown`
with `escape_formulas: false`) and `columns: "original"`; other shapes download from the start, as does
`resume: false`. An answer that does not continue the partial file gives an `:email_validation` error (status 206,
`unexpected_response`). Run one download per destination at a time.

## Verify webhooks

```elixir
# Phoenix / Plug: the raw body, read in full (at most 1 MB) before any JSON parsing
case Plug.Conn.read_body(conn, length: 1_048_576) do
  {:ok, payload, conn} ->
    case EmailValidation.verify_webhook(payload, conn.req_headers, System.fetch_env!("EV_WEBHOOK_SECRET")) do
      {:ok, %EmailValidation.WebhookEvent{type: "bulk.completed", data: data}} ->
        IO.puts("job done #{data.job_id}")
        Plug.Conn.send_resp(conn, 204, "")

      {:ok, _event} ->
        Plug.Conn.send_resp(conn, 204, "")

      {:error, %EmailValidation.WebhookVerificationError{}} ->
        Plug.Conn.send_resp(conn, 400, "invalid signature")
    end

  {:more, _partial, conn} ->
    Plug.Conn.send_resp(conn, 413, "body too large")

  {:error, _reason} ->
    Plug.Conn.send_resp(conn, 400, "could not read the body")
end
```

Headers can be Plug's `conn.req_headers`, any list of pairs or a map, with names in any case. `event.type` can also be
`webhook.test`, sent when you press **Send test** in the dashboard: answer it with a `2xx` like any other event.
`EmailValidation.sign_webhook/4` creates a valid signature for local tests.

## Constants

`EmailValidation.statuses/0`, `reasons/0`, `reasons_by_status/0`, `reason_info/0`, `actions/0`, `error_codes/0`,
`webhook_events/0`, `status?/1`, `reason?/1` and `EmailValidation.sandbox_address(reason)` mirror the API's
vocabulary. See [statuses and reasons](https://email-validation.org/docs/statuses/) and [test addresses](https://email-validation.org/docs/test-addresses/).

## Bring your own HTTP client

Pass `transport:` with a module implementing the `EmailValidation.Transport` behaviour (`request/3` returning an
`EmailValidation.Transport.Response`, or a `Transport.Error` when no answer arrived), for example to log requests or
in tests. The default `EmailValidation.Transport.HTTP` uses OTP's `:ssl`, verifies the server against the system CA
store, keeps connections alive and does not use proxies.

Your transport must never retry a request itself: a validation, upload, start or cancel that reached the service may
already have been charged or applied. Turn off your HTTP library's retries (Req: `retry: false`); OTP's `:httpc`
resends a request when a kept-alive connection closes before the answer, so do not use it for these calls. It must
also close a connection whose answer it did not read to the end instead of reusing it, or the next call can read the
previous call's late answer, another address's result. Do not cap the whole exchange with a total timeout
either: it would cut a slow but progressing 100 MB transfer. The client bounds a transport you pass even when it ignores
`request.timeout`: each attempt runs in its own process, which is stopped on a timeout.
