# Dart SDK

URL: https://email-validation.org/docs/sdks/dart/
Updated: 2026-11-28

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

The official Dart SDK is pure Dart with no dependencies, for server-side Dart: a server, a backend function, a data
job or a command-line tool you run yourself. Every operation returns a `Future`, results are typed models and errors
are typed exceptions. It needs Dart 3.3 or later.

**Not published yet.** The pub package `email_validation_sdk` is not on pub.dev 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 pub.dev (coming soon).

Keep the API key where only you can read it. A Flutter app, or any other app you ship to other people, must never
contain an API key: let the app send the address to your own backend, which holds the key and calls the API with this
SDK. The SDK is not for browsers (its HTTP client uses `dart:io`); on a public web page, use a browser key with the
[form guard](https://email-validation.org/docs/form-guard/) instead.

## Validate an address

```dart
import 'dart:io';

import 'package:email_validation_sdk/email_validation_sdk.dart';

Future<void> main() async {
  final client = EmailValidationClient(Platform.environment['EV_API_KEY'] ?? '');
  try {
    final result = await client.validate('accepted@sandbox.email-validation.org');
    print('${result.status} ${result.reason} ${result.action}'); // valid accepted send
  } finally {
    client.close();
  }
}
```

Create the client once and share it. Options are named arguments: `ipAddress`, `timeoutSeconds` (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)). Nullable
fields are nullable (`null` is JSON `null`), and a status, reason or action this SDK version does not know yet is kept
as its raw string, so a `switch` on one needs a `default`.

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

```dart
final client = EmailValidationClient(Platform.environment['EV_API_KEY'] ?? '', baseUrl: euBaseUrl);
```

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

## Futures and cancellation

Every call returns a `Future`; run several at once with `Future.wait` (keep within your
[rate limit](https://email-validation.org/docs/rate-limits/); for long lists use a bulk job). To stop a call, pass a `CancelToken` as `cancel:`
and call `cancel()` on it: the call stops at once, during a request, a retry or poll wait, or while you read a results
stream, with a `ConnectionException` of code `aborted`. A cancelled call is never retried.

```dart
final cancel = CancelToken();
final results = Future.wait([
  client.validate('accepted@sandbox.email-validation.org', cancel: cancel),
  client.validate('catch_all@sandbox.email-validation.org', cancel: cancel),
]);
// cancel.cancel() stops both, for example when the user leaves the screen
for (final r in await results) {
  print('${r.email}: ${r.status}');
}
```

## Handle errors

```dart
try {
  final result = await client.validate(address);
  print(result.status);
} on InsufficientCreditsException {
  // buy credits; nothing was charged
} on RateLimitException catch (e) {
  print('retry in ${e.retryAfter} s');
} on EmailValidationException catch (e) {
  print('${e.kind} ${e.status} ${e.code} ${e.requestId}');
}
```

Every failure of an API call is an `EmailValidationException` with `status` (0 when no answer arrived), `code`,
`message`, `requestId` and `retryAfter`. Its subclasses: `InvalidRequestException`, `AuthenticationException`,
`InsufficientCreditsException`, `PermissionDeniedException`, `NotFoundException`, `ConflictException`,
`RateLimitException`, `ServiceUnavailableException`, `ServerException` and `ConnectionException`. Wrong arguments throw
an `ArgumentError` before any request is sent.

## Retries and timeouts

```dart
final client = EmailValidationClient(
  Platform.environment['EV_API_KEY'] ?? '',
  timeout: const Duration(seconds: 30), // per attempt; an idle timeout for uploads and downloads
  maxRetries: 2, // after 429 / 503 answers
  maxRetryWait: const Duration(seconds: 10), // longer Retry-After values are returned to you
);
// one call with another timeout; its expiry is a ConnectionException with code timeout
final credits = await client.credits(requestTimeout: const Duration(seconds: 5));
print(credits.balance);
```

`429` and `503` answers are retried with backoff, honoring `Retry-After`. A daily key cap is never retried, and a
`POST` or `DELETE` (a validation, a bulk upload, start or cancel) is never sent again after a network failure or a
timeout, because it may already have been charged or applied; only `GET` requests are retried then.

`timeout` (default 30 s) bounds each attempt, not the whole call. For JSON calls it covers the whole attempt:
connecting, sending and reading the full answer. Transfers (`bulk.create` with a `file`, `bulk.results`,
`bulk.resultsStream` and `bulk.download`) use it as an idle timeout instead: the attempt fails only when no byte was
sent or received for that long. So a slow but progressing upload or download of a large file is never cut, and no timer
runs while your code is busy between two reads of a stream. A large upload gets up to 32 s more: while it is sent, and
while its answer is awaited, that bound grows by the time the kernel's send buffer needs to drain (`min(size, 4 MiB)` at
128 KiB/s). A `bulk.create` with a large `emails` list gets the same allowance on top of its timeout. `requestTimeout:`
replaces the timeout for one call.

A `bulk.create` that ends in a `timeout` or `connection_error`, or is cancelled (code `aborted`), may still have
created the job: the service can receive the whole list after the SDK stopped waiting, and unless you pass
`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 `webhookEndpointId`, and only when the job ends.

## Credits, usage and status

```dart
final credits = await client.credits(); // balance, debt, pending, lots
// the last 90 days by default; pass from / to as YYYY-MM-DD for another range
final usage = await client.usage(groupBy: UsageGroupBy.day);
final status = await client.status();
print('${credits.balance} ${usage.days.length} ${status.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:

```dart
var job = await client.bulk.create(
  emails: ['accepted@sandbox.email-validation.org', 'catch_all@sandbox.email-validation.org'],
);

job = await client.bulk.wait(job.id, onProgress: (j) => print('${j.status} ${j.processed}'));
switch (job.status) {
  case BulkJobStatus.completed:
    // only some rows, in memory
    final csv = await client.bulk.results(job.id, filter: ResultsFilter.statuses([Status.valid, Status.catchAll]));
    print('${csv.length} bytes');

    // or stream the CSV into a file; after a failure, the same call resumes this job's partial file
    final size = await client.bulk.download(job.id, 'results.csv');
    print('saved $size bytes');
  case BulkJobStatus.ready:
    // it could not start: job.errorCode is e.g. insufficient_credits (buy credits, then client.bulk.start)
    print(job.errorCode);
  default:
    print('the job ended ${job.status}');
}
```

Or from a CSV file (up to 100 MB, read once and sent with its length), then fetch the results as above:

```dart
var job = await client.bulk.create(file: BulkFile.path('customers.csv'), columnName: 'email', hasHeader: true);
job = await client.bulk.wait(job.id);
print('the job ended ${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:` to give up earlier. Also:
`bulk.get`, `bulk.start` for jobs created with `start: false` (call it before `wait`), `bulk.cancel`, and
`bulk.resultsStream`, which returns a `Stream<List<int>>` for large files. A file can be `BulkFile.path`,
`BulkFile.bytes`, `BulkFile.text` (the content itself) or `BulkFile.stream`.

`filter` is `ResultsFilter.all`, one status (`ResultsFilter.status(Status.valid)`) or several
(`ResultsFilter.statuses([...])`); a filter with no status, `all` inside a list and any name that is not one of the
[five statuses](https://email-validation.org/docs/statuses/) are refused before any request.

`bulk.download(jobId, path)` writes the result CSV into a file without holding it in memory and returns the file's
size. It writes into `<path>.<job id>.<shape>.part` beside `path` (e.g.
`results.csv.job_7Hq2LmX9cV4bN8tR1zK6wD.all-original-escaped.part`) and moves that file onto `path` when the download
is complete: a file already at `path` is replaced only then, and left as it was if the call fails, so you can reuse
the same path for several jobs. A failure part-way keeps the partial file: with `resume` (the default) the next call
for the same job and options asks only for the rest (`Range: bytes=<size>-`), never the file at `path`, and a second
call after success downloads the file again. Resuming works for every row (the default) or a single status of `valid`, `invalid` or `unknown` with
`escapeFormulas: false`, with the original columns; other shapes start again from the first byte, as does
`resume: false`. A partial file that does not continue as the answer says throws an `EmailValidationException` with
code `unexpected_response`. Run one download per destination at a time. `bulk.download` and `BulkFile.path` need files,
so they are not available on the web.

## Verify webhooks

```dart
import 'dart:io';

import 'package:email_validation_sdk/email_validation_sdk.dart';

Future<void> main() async {
  final secret = Platform.environment['EV_WEBHOOK_SECRET'] ?? '';
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  await for (final request in server) {
    final body = await request.fold<List<int>>([], (all, chunk) => all..addAll(chunk)); // the raw body
    try {
      final event = verifyWebhook(body, request.headers, secret);
      if (event.type == WebhookEventType.bulkCompleted) {
        print('job done ${event.bulkData.jobId}');
      }
      request.response.statusCode = HttpStatus.noContent;
    } on WebhookVerificationException {
      request.response.statusCode = HttpStatus.badRequest;
    }
    await request.response.close();
  }
}
```

The headers can also be a `Map<String, String>` (shelf's `request.headers`) or a `Map<String, List<String>>`.
`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. `signWebhook` creates a valid signature for local tests.

## Constants

`statuses`, `reasons`, `reasonsByStatus`, `reasonInfo`, `actions`, `errorCodes`, `webhookEvents`, named values such
as `Status.valid` and `Reason.accepted`, and `sandboxAddress(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

Implement the `Transport` interface (`send(TransportRequest)` and `close()`) and pass it as `transport:`, for example
to use another HTTP stack, a proxy library or a fake in tests; `HttpTransport()` is the built-in one, which you can
wrap. A transport must never follow a redirect (return the `3xx` answer), never retry by itself (a validation, bulk
upload, start or cancel may already have been charged or applied), send every request other than `GET` on a fresh
connection, send bodies with their length, and stop when the request's `aborted` future completes. The client enforces its
timeouts itself, so a transport cannot hang a call.
