# Email Validation API Code Samples in Java

URL: https://email-validation.org/docs/code-samples/java/
Updated: 2026-11-25

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

Copy-paste Java 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](https://email-validation.org/docs/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](https://email-validation.org/docs/eu-data-residency/)).

## With the official SDK

The [official Java SDK](https://email-validation.org/docs/sdks/java/) (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.

**Java**

```java
import org.email_validation.sdk.EmailValidationClient;
import org.email_validation.sdk.EmailValidationException;
import org.email_validation.sdk.InsufficientCreditsException;
import org.email_validation.sdk.ValidationResult;

try (EmailValidationClient client = EmailValidationClient.builder(System.getenv("EV_API_KEY")).build()) {
  ValidationResult result = client.validate("accepted@sandbox.email-validation.org");
  System.out.println(result.status() + " " + result.reason() + " " + result.action()); // valid accepted send
} catch (InsufficientCreditsException e) {
  System.out.println("buy credits; nothing was charged");
} catch (EmailValidationException e) {
  System.out.println(e.code() + " " + e.requestId().orElse("-"));
}
```

## Validate an address

**Java**

```java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateEmail {
    private static final HttpClient CLIENT =
            HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

    static String validate(String email, int attempts) throws IOException, InterruptedException {
        // Build the JSON with your JSON library in real code; this address needs no escaping.
        String json = "{\"email\":\"" + email + "\"}";
        for (int attempt = 1; ; attempt++) {
            HttpRequest 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();
            HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
            int 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.
            long wait = Math.max(1, response.headers().firstValueAsLong("Retry-After").orElse(1));
            boolean dailyCap = response.body().contains("\"key_daily_cap\"");
            if ((status == 429 || status == 503) && !dailyCap && wait <= 10 && attempt < attempts) {
                Thread.sleep(wait * 1000);
                continue;
            }
            throw new IOException("HTTP " + status + ": " + response.body());
        }
    }

    public static void main(String[] args) throws Exception {
        String body = validate("accepted@sandbox.email-validation.org", 3);
        // Read the JSON with Jackson, Gson or similar in real code. Print the verdict only, never the address itself.
        StringBuilder verdict = new StringBuilder();
        for (String field : new String[] {"status", "reason", "action", "credits_used"}) {
            Matcher m = Pattern.compile("\"" + field + "\"\\s*:\\s*\"?([^\",}]*)").matcher(body);
            verdict.append(m.find() ? m.group(1) : "-").append(' ');
        }
        System.out.println(verdict.toString().trim());
    }
}
```

## Verify a webhook

**Java**

```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class WebhookVerifier {
    /** Throws SecurityException unless the delivery is authentic and recent. */
    public static void verify(String rawBody, String id, String timestamp, String signatures, String secret)
            throws Exception {
        if (id == null || timestamp == null || signatures == null) {
            throw new SecurityException("Missing webhook headers");
        }
        if (!timestamp.matches("\\d{1,12}")
                || Math.abs(Instant.now().getEpochSecond() - Long.parseLong(timestamp)) > 300) {
            throw new SecurityException("Timestamp outside tolerance");
        }
        byte[] key = Base64.getDecoder().decode(secret.replaceFirst("^whsec_", ""));
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        byte[] expected = mac.doFinal((id + "." + timestamp + "." + rawBody).getBytes(StandardCharsets.UTF_8));
        for (String entry : signatures.split(" ")) {
            String[] parts = entry.split(",", 2);
            if (parts.length != 2 || !parts[0].equals("v1")) {
                continue;
            }
            try {
                if (MessageDigest.isEqual(Base64.getDecoder().decode(parts[1]), expected)) {
                    return;
                }
            } catch (IllegalArgumentException ignored) {
                // not base64: try the next signature
            }
        }
        throw new SecurityException("No valid signature");
    }
}
```

## Other calls

- Read the credit balance: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#credits)).
- Create a bulk job: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#bulk)).

## 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](https://email-validation.org/docs/api-reference/).
