EmailValidation

main

Official Swift client for the email-validation.org email validation API
email-validation-dev/email-validation-swift

email-validation.org Swift SDK

Official Swift client for the email-validation.org API: validate single addresses, read credits, usage and service status, run bulk jobs and verify webhook signatures. async/await, Sendable, Swift 6 strict concurrency, typed results and typed errors. One dependency, swift-crypto, for HMAC-SHA256 (it uses CryptoKit on Apple platforms). Needs the Swift 6.0 tools or later (Swift 6 language mode) and macOS 12, iOS 15, tvOS 15 or watchOS 8; tested with Swift 6.4 on macOS. It is written to build on Linux too (with FoundationNetworking), but Linux is not tested yet.

Documentation: https://email-validation.org/docs/sdks/swift/

Install

Swift Package Manager, in Package.swift:

dependencies: [
    .package(url: "https://github.com/email-validation-dev/email-validation-swift.git", from: "1.1.0")
],
targets: [
    .target(name: "MyApp", dependencies: [.product(name: "EmailValidation", package: "email-validation-swift")])
]

In Xcode: File > Add Package Dependencies…, then add the EmailValidation library to your target.

Quick start

import EmailValidation
import Foundation

let client = try EmailValidationClient(apiKey: ProcessInfo.processInfo.environment["EV_API_KEY"] ?? "")
let result = try await client.validate("accepted@sandbox.email-validation.org")  // free test address
print(result.status, result.reason, result.action)  // valid accepted send

Every result has one of five statuses: valid, invalid, catch_all, unknown or disposable; reason says why and action what to do. Addresses <reason>@sandbox.email-validation.org are free and answer that reason (Vocabulary.sandboxAddress(.catchAll)).

Keep the API key on your server: do not ship it inside an app. Construct the client once and share it: it is Sendable and safe to use from many tasks.

Client options

let client = try EmailValidationClient(
    apiKey: key,
    baseURL: "https://api.email-validation.org",  // default; Vocabulary.euBaseURL for the EU
    timeout: 30,  // seconds per attempt; must be a finite number above 0
    maxRetries: 2,  // retries after 429/503 answers and failed reads; negative counts as 0
    maxRetryWait: 10,  // longest single wait (seconds) the client accepts before giving up
    transport: nil  // default URLSessionTransport()
)
  • timeout bounds each attempt. For JSON calls (validate, credits, bulk.get, …) it is a hard bound on the whole attempt: connect, send and read the full answer. For transfers (bulk.create(file:…) and the other upload forms, bulk.results, resultsStream, download) it is an idle timeout: they fail only when no byte was sent or received for that long, so a 100 MB file on a slow link is not cut while it moves. URLSession reports upload progress per block handed to the system, not as bytes leave, so until the answer starts an upload may also be silent for timeout + min(size, 4 MiB) ÷ 128 KiB/s (at most timeout + 32 s) while the send buffer drains.
  • Every operation takes requestTimeout: (seconds, above 0) to replace timeout for that one call, with the same JSON / transfer meaning (for bulk.wait, for each poll).
  • EU data residency (validated and stored in the EU): baseURL: Vocabulary.euBaseURL calls https://api-eu.email-validation.org instead of the default https://api.email-validation.org. See https://email-validation.org/docs/eu-data-residency/.
let euClient = try EmailValidationClient(apiKey: key, baseURL: Vocabulary.euBaseURL)

The initializer throws InvalidArgumentError for an empty key, a key containing whitespace, a base URL that does not start with http:// or https://, or a timeout that is not a finite number above 0. client.configuration shows the options; its text forms (description, dump) never show the key.

Validate an address

let result = try await client.validate(
    "accepted@sandbox.email-validation.org",
    ipAddress: "203.0.113.7",  // the IP the person used when they gave you the address (optional)
    timeout: 10,  // seconds the service may spend on the check, 5–15 (default 15)
    fresh: true,  // check again even if it was checked in the last 12 months (default false)
    requestTimeout: 20  // this call's client timeout (default: the client's `timeout`)
)
switch result.action {
case .send: print("send")
case .sendWithCaution: print("send with caution")
case .remove: print("remove")
case .retryLater: print("retry later")
default: print("new action: \(result.action.rawValue)")  // a value added to the API after this release
}

A check costs 1 credit, except unknown results, malformed addresses and sandbox addresses (creditsUsed is 0). Without fresh, a definite result from a check of the same address in the last 12 months may be returned; processedAt is when the answer was produced. Keep the client timeout a few seconds above the timeout you pass here.

ValidationResult has the API's fields with Swift names: email, status, reason, action, account, domain, didYouMean, freeEmail, roleAccount, disposable, catchAllDomain, mxFound, mxRecord, smtpProvider, domainAgeDays, processedAt, creditsUsed, requestId. Nullable fields are optionals. Times are the API's ISO 8601 UTC strings. Encoding a model with JSONEncoder gives back the API's JSON (snake_case keys, null kept).

Vocabulary values (Status, Reason, Action, SmtpProvider, BulkJobStatus, BulkJobErrorCode, ComponentState, WebhookEventType, ErrorCode) are open string types with named constants (.valid, .catchAll, …). A value added to the API after this release still decodes: it keeps its raw string and isKnown is false. A switch over one needs a default: branch.

Credits, usage and status

let credits = try await client.credits()
print(credits.balance, credits.debt, credits.pending)
for lot in credits.lots { print(lot.remaining, lot.expiresAt) }  // soonest-expiring first

let usage = try await client.usage(from: "2026-10-01", to: "2026-10-20")  // by day (default)
for day in usage.days ?? [] { print(day.date, day.creditsUsed, day.byStatus.valid) }

let byKey = try await client.usage(from: "2026-10-01", to: "2026-10-20", groupBy: .key)
for key in byKey.keys ?? [] { print(key.name ?? "deleted key", key.last4 ?? "", key.creditsUsed) }

let status = try await client.status()  // no credits used
print(status.status, status.components.api, status.updatedAt)

Bulk jobs

Bulk jobs need a key with the bulk scope.

// From a list (sent as JSON, up to 100,000 addresses)…
var job = try await client.bulk.create(emails: [
    "accepted@sandbox.email-validation.org", "no_mailbox@sandbox.email-validation.org",
])

// …or from a CSV or plain-text file (up to 100 MB): a file URL, Data, String or an InputStream.
job = try await client.bulk.create(
    fileAt: URL(fileURLWithPath: "list.csv"),
    contentType: .csv,  // or .plainText (one address per line)
    column: "email",  // header name or 1-based index (detected when omitted)
    hasHeader: true,  // detected when omitted
    start: false,  // default true; false leaves the job in `ready` until you call start
    webhookEndpointId: nil  // a registered endpoint to notify when the job ends
)
job = try await client.bulk.create(stream: InputStream(fileAtPath: "list.txt")!, contentType: .plainText)

job = try await client.bulk.start(job.id)  // only for a job created with start: false; call it before wait
job = try await client.bulk.wait(job.id, interval: 5, timeout: 3600) { job in
    print(job.status, job.processed)
}
guard job.status == .completed else {
    // failed, cancelled, expired, or `ready` with an errorCode (its start was refused, e.g. insufficient_credits:
    // buy credits, then call start).
    throw MyError.jobDidNotComplete(job.status, job.errorCode)
}

let csv = try await client.bulk.results(job.id)  // whole file in memory
let some = try await client.bulk.results(job.id, filter: [.valid, .catchAll], columns: .emailOnly)

// Large files: stream the bytes…
let download = try await client.bulk.resultsStream(job.id, filter: .all)
for try await chunk in download { fileHandle.write(chunk) }

// …or a byte range (filter .all, or one status with escapeFormulas false; columns .original)…
let part = try await client.bulk.results(job.id, filter: .all, range: "bytes=1048576-")

// …or straight into a file: a second call resumes a cut download where it stopped.
let size = try await client.bulk.download(job.id, to: URL(fileURLWithPath: "results.csv"))
print(csv.count, some.count, part.count, size)
Method Request
bulk.create(emails:…) / create(file:…) / create(fileAt:…) / create(stream:…) POST /v1/bulk (202)
bulk.get(_:) GET /v1/bulk/{id}
bulk.start(_:) POST /v1/bulk/{id}/start (credits are held now)
bulk.cancel(_:) DELETE /v1/bulk/{id} (unused credits are returned)
bulk.results(_:filter:columns:escapeFormulas:range:) GET /v1/bulk/{id}/results → Data
bulk.resultsStream(…) same, as a ResultsDownload (an AsyncSequence of Data chunks)
bulk.download(_:to:filter:columns:escapeFormulas:resume:) same, streamed into a file; returns its size
bulk.wait(_:interval:timeout:onProgress:) polls bulk.get
  • Uploads are sent with their length (never chunked) and held in memory once; a file URL is mapped rather than copied when the system allows it, and a stream is read to its end before anything is sent, so a 429/503 retry re-sends the same bytes.
  • wait returns once the job is completed, failed, cancelled or expired, or ready with an errorCode. The interval is at least 1 second (default 5). With timeout, it throws a .connection error with code .timeout when the next poll would pass the deadline. A job created with start: false waits in ready until you call start, so call start before wait.
  • Job ids are checked locally (job_ followed by 22 letters and digits): a malformed id throws an .invalidRequest error with status 0 and sends nothing.
  • resultsStream reads from the network only as fast as you iterate (at most about 1 MB waits in memory). Each read waits at most timeout for data, and there is no limit while you process a chunk. A failure while iterating is an EmailValidationError (.timeout, .connectionError); cancelling the iterating task throws .aborted, and an answer cut short of its Content-Length throws .connectionError. One case URLSession cannot see: the shapes the server builds on the fly (several statuses, .emailOnly, one status with formula escaping) arrive chunked, without a length, and a connection cut exactly between two chunks ends like a complete answer. The shapes that can resume (filter .all, or one status with escapeFormulas: false; columns .original) always have a length, so for a large file prefer one of them (with download).
  • With range, the answer must be a 206 part. Shapes the server cannot serve in parts (several statuses, .emailOnly, one status with formula escaping) are answered with the whole file; the SDK then throws an .invalidRequest error (and closes the answer unread) instead of returning it, so joined parts never duplicate data.
  • download(_:to:…) streams into the file. With resume (default) and a non-empty file there, it asks for the missing bytes (Range: bytes=<size>-) and appends them; a file that is already complete is left as is (the answer is 416 with Content-Range: bytes */<size>); any other answer leaves the file untouched and throws. Resuming needs filter .all (or one status with escapeFormulas: false) and columns .original, otherwise it throws InvalidArgumentError. A failure while writing leaves the partial file for the next call to resume.
  • A filter with a status this SDK does not know, or an empty list, throws InvalidArgumentError before sending.
  • The CSV is returned unchanged; the SDK never decodes it. Check job.status before downloading.

Handle errors

Every failure of an API call, including one while you iterate a resultsStream, is an EmailValidationError. Branch on kind or code, never on message.

do {
    let result = try await client.validate("accepted@sandbox.email-validation.org")
    print(result.status)
} catch let error as EmailValidationError {
    switch error.kind {
    case .insufficientCredits: print("buy credits")
    case .rateLimit: print("slow down, retry after \(error.retryAfter ?? 1) s")
    case .authentication: print("check the API key")
    case .connection where error.isCancellation: print("cancelled")
    default: print(error.kind.canonicalName, error.status, error.code, error.requestId ?? "-")
    }
}
Kind (canonicalName) When
.invalidRequest (InvalidRequestError) 400, 411, 413, other 4xx, malformed job id (status 0), range answered without 206
.authentication (AuthenticationError) 401
.insufficientCredits (InsufficientCreditsError) 402 (nothing charged)
.permissionDenied (PermissionDeniedError) 403
.notFound (NotFoundError) 404
.conflict (ConflictError) 409
.rateLimit (RateLimitError) 429
.serviceUnavailable (ServiceUnavailableError) 503
.server (ServerError) 500, other 5xx, any other non-2xx answer (a redirect is never followed)
.connection (ConnectionError) no answer: connection_error, timeout, aborted (task cancelled), bulk.wait deadline
.general (EmailValidationError) a 2xx answer that is not JSON (unexpected_response)

Every error has status (0 when no answer arrived), code (one of the 15 API codes in ErrorCode.apiCodes, or connection_error, timeout, unexpected_response, aborted), message, requestId (quote it to support), retryAfter (seconds, from Retry-After) and underlyingError. An answer without our error envelope (or with an unknown code) has code unexpected_response. The error's text shows kind, status, code and request id; it never contains the API key, the request body or the checked address.

Invalid arguments the type system cannot catch (client options, requestTimeout, a results filter with an unknown status, a download shape that cannot resume) throw InvalidArgumentError instead, before any request.

Retries, timeouts and cancellation

  • 429 and 503 answers are never charged, so they are retried for every method (POST included), up to maxRetries times, waiting Retry-After seconds (digits or an HTTP date) or, without it, an exponential backoff with jitter (0.25–0.5 s, 0.5–1 s, 1–2 s, … capped at 4–8 s). If the wait would be longer than maxRetryWait, the error is thrown at once. key_daily_cap (429) is never retried: it resets the next day.
  • Network failures and timeouts are retried only for reads (GET). A validate, a bulk upload, start or cancel that reached the service may already have been charged or applied, so it is never sent again, by the SDK or by the HTTP stack underneath (tested against a server that reads the request and drops the connection).
  • Nothing else is retried (400–428, 500, 502, 504, …). The API has no idempotency header. A results stream or download is not retried once a byte reached you; download resumes on the next call.
  • timeout bounds each attempt: the whole attempt for JSON calls, an idle timeout for transfers (see Client options). requestTimeout: replaces it for one call. The client enforces both itself, so a custom transport that ignores them cannot hang a call.
  • Cancellation: cancel the calling Task. A request, a retry wait, a bulk.wait poll or a read of a results stream stops at once and throws EmailValidationError with kind .connection, code .aborted and isCancellation == true (the underlyingError is the CancellationError). Nothing is retried after a cancellation.
let task = Task { try await client.bulk.wait(job.id, requestTimeout: 10) }
task.cancel()  // the wait throws .aborted

Verify webhooks

Deliveries follow the Standard Webhooks scheme. Pass the raw request body and the headers:

do {
    let event = try verifyWebhook(payload: rawBody, headers: requestHeaders, secret: "whsec_…")
    switch event.data {
    case .bulk(let data): print(event.type, data.jobId, data.status, data.creditsCharged)
    case .creditsLow(let data): print("balance \(data.balance) below \(data.threshold)")
    case .creditsExpiring(let data): print("\(data.credits) credits expire at \(data.expiresAt)")
    case .webhookTest(let data): print("test from endpoint \(data.endpointId)")
    case .other(let json): print("new event type \(event.type): \(json)")
    }
} catch let error as WebhookVerificationError {
    print(error.reason)  // answer 400
}
  • payload is Data or String; headers is [String: String] or [String: [String]] (names in any case; several values are joined with a space, and signatures joined with , still verify). tolerance (default 300 s, Vocabulary.defaultWebhookTolerance) and now are optional.
  • Checks, in order: the webhook-id, webhook-timestamp and webhook-signature headers are present; the timestamp is 1–12 digits and within the tolerance; the secret is whsec_ + strict base64; one v1 signature matches (compared in constant time); the body is a JSON object (any object is an event, so new fields and types still arrive). Each failure has its own WebhookVerificationError.Reason (missingHeaders, invalidTimestamp, timestampOutOfTolerance, missingSecret, invalidSecret, noMatchingSignature, invalidBody).
  • Deduplicate on the webhook-id header: retries reuse it. Answer with a 2xx quickly and do the work afterwards.
  • webhook.test events come from "Send test" in the dashboard.
  • signWebhook(msgId:timestamp:payload:secret:) builds a webhook-signature value to test your endpoint locally.

Constants

Vocabulary holds the API's lists and helpers: statuses, reasons, reasonsByStatus, reasonInfo (status and action of every reason), actions, smtpProviders, bulkJobStatuses, terminalBulkJobStatuses, bulkJobErrorCodes, errorCodes, clientErrorCodes, webhookEvents, defaultBaseURL, euBaseURL, sandboxDomain, defaultWebhookTolerance, isStatus(_:), isReason(_:) and sandboxAddress(_:). Each vocabulary type also has known (and Reason.status / Reason.action). EmailValidationClient.sdkVersion is 1.1.0; the client sends User-Agent: email-validation-swift/1.1.0.

Bring your own HTTP client

The client talks to a small protocol, HTTPTransport: send(_ request: HTTPRequest) async throws -> HTTPResponse and optionally stream(_:) for downloads (without it, results, resultsStream and download are served from send, so timeout then bounds the whole download). The default, URLSessionTransport, owns its URLSession, refuses redirects, stores no cookies and caches nothing; pass URLSessionTransport(configuration:) to set a proxy or other connection options.

A custom transport must not follow redirects, should use request.timeout as an idle timeout and request.deadline (set for JSON calls, nil for transfers) as a bound on the whole call (throw TransportError(.timeout)), throw TransportError(.connection) when no answer arrived, never re-send a request by itself, and let the task's cancellation surface. The client bounds every attempt and every download read itself as well, so a transport that ignores its timeouts cannot hang a call. It cannot see the progress of a custom transport's upload, so it bounds a file upload sent through one by timeout + size ÷ 128 KiB/s plus timeout for the answer (100 MB: about 13.5 minutes); the built-in transport keeps its own idle timer instead. Tests can pass a stub transport and never touch the network.

Privacy

  • The API key travels only in the Authorization header: never in a URL, a log line, an error, or the text and mirror forms (description, dump) of the client, its configuration or an HTTPRequest (which also hides the body, where the checked address is).
  • The SDK writes nothing to stdout or stderr and has no telemetry.

Licence

MIT, see LICENSE.

Description

  • Swift Tools 6.0.0
View More Packages from this Author

Dependencies

Last updated: Sat Nov 28 2026 17:20:13 GMT-1000 (Hawaii-Aleutian Standard Time)