# Perl SDK

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

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

The official Perl SDK returns read-only result objects, dies with typed errors and retries the answers that are never
charged. It needs Perl 5.14 or later and only Perl core modules (`HTTP::Tiny`, `JSON::PP`, `Digest::SHA`); HTTPS also
needs `IO::Socket::SSL` and `Net::SSLeay`, which the system Perl of macOS has.

**Not published yet.** The CPAN module `EmailValidation::SDK` is not on CPAN 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 `EmailValidation::SDK` is on CPAN (coming soon).

The classes live under `EmailValidation::`; `use EmailValidation::SDK;` loads them all. HTTPS needs `IO::Socket::SSL` and
`Net::SSLeay` (not core modules: install them with your system's packages or `cpanm IO::Socket::SSL` where they are
missing), and `HTTP::Tiny` 0.076 or later (in the core from Perl 5.30).

## Validate an address

```perl
use strict;
use warnings;
use EmailValidation::SDK;

my $client = EmailValidation::Client->new(api_key => $ENV{EV_API_KEY});

my $result = $client->validate('accepted@sandbox.email-validation.org');
print join(' ', $result->status, $result->reason, $result->action), "\n";    # valid accepted send
```

Build the client once and reuse it: it keeps one connection alive for its `GET` requests. Options: `ip_address`,
`timeout` (seconds the check may take, 5–15) and `fresh`. `fresh => 1` 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)). Results are read-only objects with the API's field names;
`to_hash` and `to_json` give back the API's fields.

## 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::Constants::EU_BASE_URL`:

```perl
my $client = EmailValidation::Client->new(
    api_key  => $ENV{EV_API_KEY},
    base_url => EmailValidation::Constants::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

The Perl client is synchronous: each call returns when the answer is in. Use one client per process (or per thread),
stay within your [rate limit](https://email-validation.org/docs/rate-limits/), or use a bulk job for lists.

## Handle errors

```perl
my $result = eval { $client->validate('accepted@sandbox.email-validation.org') };
if (my $error = $@) {
    die $error unless EmailValidation::Error->is_error($error);
    if ($error->isa('EmailValidation::InsufficientCreditsError')) {
        print "buy credits; nothing was charged\n";
    }
    elsif ($error->isa('EmailValidation::RateLimitError')) {
        printf "retry in %s seconds\n", $error->retry_after // 'a few';
    }
    else {
        printf "%s %d %s\n", $error->code, $error->status, $error->request_id // '-';
    }
}
```

Every error is an `EmailValidation::Error` with `status` (0 when no answer arrived), `code`, `request_id` and
`retry_after`. Subclasses: `InvalidRequestError`, `AuthenticationError`, `InsufficientCreditsError`,
`PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `ServiceUnavailableError`, `ServerError`
and `ConnectionError`, all under `EmailValidation::`. Wrong arguments die with an `EmailValidation::ArgumentError`
before any request is sent.

## Retries and timeouts

```perl
my $client = EmailValidation::Client->new(
    api_key        => $ENV{EV_API_KEY},
    timeout        => 30,    # seconds per attempt
    max_retries    => 2,     # after 429 / 503 answers
    max_retry_wait => 10,    # longer Retry-After values die instead of being waited out
);

my $credits = $client->credits(request_timeout => 5);    # every method takes request_timeout for that one call
```

`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: the built-in transport sends each of them once, on a fresh connection.

`timeout` bounds each attempt of a JSON call as a whole. Transfers (a file upload, results and downloads) use it as an
idle timeout instead: 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 `on_chunk` code is busy. `request_timeout` replaces `timeout` for
one call (for `wait`, each poll). An answer cut short by a closed connection dies with a `ConnectionError`
`connection_error`, never passes as complete. Perl has no cancellation for blocking calls; bound a call with
`request_timeout` instead.

A `bulk->create` that ends in a `timeout` or `connection_error` may still have created the job: the service can
receive the whole list after the SDK stopped waiting, and unless you passed `start => 0` 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

```perl
my $credits = $client->credits;    # balance, debt, pending, lots
# the last 90 days by default; pass from / to as YYYY-MM-DD for another range
my $usage  = $client->usage(group_by => 'day');
my $status = $client->status;
```

## 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:

```perl
my $job = $client->bulk->create(emails => ['accepted@sandbox.email-validation.org', 'catch_all@sandbox.email-validation.org']);

$job = $client->bulk->wait($job->id, on_progress => sub { printf "%s %d\n", $_[0]->status, $_[0]->processed });

if ($job->status eq EmailValidation::BulkJobStatus::COMPLETED) {
    my $csv   = $client->bulk->results($job->id, filter => ['valid', 'catch_all']);
    my $bytes = $client->bulk->download($job->id, 'results.csv');    # streamed to a file, resumable
}
elsif ($job->is_stuck) {
    print 'could not start: ', $job->error_code, "\n";    # e.g. insufficient_credits: buy credits, then start
}
```

Or from a CSV file (up to 100 MB: a path, a filehandle, the content or a reference to it), then fetch the
results as above:

```perl
my $job = $client->bulk->create(file_path => 'customers.csv', column => 'email', has_header => 1);
$job = $client->bulk->wait($job->id);
print $job->status, "\n";
```

`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` (seconds) to give up earlier. Also:
`get`, `start` for jobs created with `start => 0` (call it before `wait`), `cancel`, and `results` with `on_chunk`,
which streams large files in chunks.

`download($job_id, $path)` writes the results into a file without holding them in memory and returns the file's
length. It downloads into `<path>.<job id>.<shape>.part` beside `$path` and moves that file onto `$path` when it is
complete: a file already at `$path` is replaced only then, and stays as it was if the call fails, so the same path
can be reused for every job. With `resume => 1` (the default) a call after a failure continues that job's own partial
file, never the file at `$path`. Resuming works for `filter => 'all'` (or a single status of `valid`, `invalid` or `unknown` with `escape_formulas => 0`) and
`columns => 'original'`; other shapes start from the beginning, and `resume => 0` starts over (call again with it
after an `unexpected_response` error). A symbolic link at `$path` is followed (its target is replaced) and the file
keeps its permissions; a directory or other non-file at `$path` is refused before any request. Leftover `*.part`
files of other jobs or options beside the destination can be deleted. Run one download per destination at a time.

## Verify webhooks

```perl
# a PSGI application (Plack, Dancer2 or Mojolicious)
my $app = sub {
    my ($env) = @_;
    my ( $payload, $chunk ) = ( '', '' );    # the raw body, read in full (at most 1 MB) before any JSON parsing
    while ( $env->{'psgi.input'}->read( $chunk, 65536 ) ) {    # a read can return less; 0 at the end
        $payload .= $chunk;
        return [413, [], ['body too large']] if length $payload > 1_048_576;
    }
    my $event = eval { EmailValidation::Webhooks::verify_webhook($payload, $env, $ENV{EV_WEBHOOK_SECRET}) };
    return [400, [], ['invalid signature']] if !$event;

    print 'job done ', $event->data->job_id, "\n" if $event->type eq 'bulk.completed';
    return [204, [], []];
};
```

Headers can be a hash reference with names in any case, a PSGI or CGI environment, name/value pairs, or a headers
object such as `HTTP::Headers` or `Mojo::Headers`. `$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::Webhooks::sign_webhook`
creates a valid signature for local tests.

## Constants

`EmailValidation::Constants` exports `STATUSES`, `REASONS`, `REASONS_BY_STATUS`, `REASON_INFO`, `ACTIONS`,
`ERROR_CODES`, `WEBHOOK_EVENTS`, `EU_BASE_URL` and `sandbox_address($reason)` on request; the named values live in
`EmailValidation::Status`, `Reason`, `Action`, `BulkJobStatus` and `ErrorCode`. They 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 any object that has `call($request)` and returns an `EmailValidation::HttpResponse` (or dies
with an `EmailValidation::TransportError` when no answer arrived), for example to log requests or in tests. The
default `EmailValidation::Transport::HTTPTiny` verifies TLS certificates, never follows a redirect, keeps one
connection alive for `GET` requests and honors the standard proxy environment variables.

Your transport must apply `$request->timeout` itself (Perl cannot interrupt a blocking call from outside) and must
never retry a request: a validation, upload, start or cancel that reached the service may already have been charged
or applied. HTTP::Tiny's own `request` method resends a `GET` or `DELETE` (a cancel) once when the connection breaks,
so send every request other than a `GET` on a fresh connection. 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.
