Code samples · Kotlin

Kotlin code samples

Copy-paste Kotlin 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.

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

With the official SDK

The official Kotlin SDK (coming soon to its registry) 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.

Kotlin

import org.email_validation.kotlin.EmailValidationClient
import org.email_validation.kotlin.EmailValidationException
import org.email_validation.kotlin.InsufficientCreditsException

suspend fun main() {
    EmailValidationClient(System.getenv("EV_API_KEY")).use { client ->
        try {
            val result = client.validate("accepted@sandbox.email-validation.org")
            println("${result.status} ${result.reason} ${result.action}") // valid accepted send
        } catch (e: InsufficientCreditsException) {
            println("buy credits; nothing was charged")
        } catch (e: EmailValidationException) {
            println("${e.code} ${e.requestId}")
        }
    }
}

Validate an address

Kotlin

// Plain JDK 11+ HTTP client; parse the JSON with kotlinx.serialization, Jackson or Moshi in real code.
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration

val client: HttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()

fun validate(email: String, attempts: Int = 3): String {
    // Build the JSON with your JSON library in real code; this address needs no escaping.
    val json = """{"email":"$email"}"""
    var attempt = 1
    while (true) {
        val request = HttpRequest.newBuilder(URI.create("https://api.email-validation.org/v1/validate"))
            .timeout(Duration.ofSeconds(20))
            .header("Authorization", "Bearer ${System.getenv("EV_API_KEY")}")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build()
        val response = client.send(request, HttpResponse.BodyHandlers.ofString())
        val status = response.statusCode()
        if (status == 200) return response.body()
        // Never wait out a long Retry-After: key_daily_cap lasts until the next UTC day.
        val wait = maxOf(1L, response.headers().firstValueAsLong("Retry-After").orElse(1L))
        val dailyCap = response.body().contains("\"key_daily_cap\"")
        if ((status == 429 || status == 503) && !dailyCap && wait <= 10 && attempt < attempts) {
            Thread.sleep(wait * 1000)
            attempt++
            continue
        }
        error("HTTP $status: ${response.body()}")
    }
}

fun main() {
    val body = validate("accepted@sandbox.email-validation.org")
    // Read the JSON with kotlinx.serialization, Jackson or Moshi in real code. Print the verdict only, never the address.
    val verdict = listOf("status", "reason", "action", "credits_used").map { field ->
        Regex("\"$field\"\\s*:\\s*\"?([^\",}]*)").find(body)?.groupValues?.get(1) ?: "-"
    }
    println(verdict.joinToString(" "))
}

Other calls

  • Read the credit balance: samples in curl, JavaScript and Python (all code samples).
  • Create a bulk job: samples in curl, JavaScript and Python (all code samples).
  • Verify a webhook: samples on Webhooks and in JavaScript, TypeScript, Python, PHP, Ruby, Go, Java and C# (all code samples).

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.

Updated · Maintained by: Email Validation LLC

Need help? Contact support, or ask the help chat. Something wrong or missing on this page? Tell us