Protect new mailboxesFresh mailboxes burn fast on a dirty list

Verify every lead before the first send and keep bounces low from day one.

Verify 25 emails free →
Product Bulk verificationReal-time APISignup form widget Catch-all detectionRole and disposable flagsFree email checker
Solutions Cold email agenciesSales teams and SDRsDevelopers and SaaS InstantlySmartleadApollolemlistClayHubSpotMailchimpWoodpeckerReply.ioSaleshandyZapierGoogle SheetsMaken8n All integrations
Mailboxes Google Workspace mailboxesOutlook mailboxesNew cold domain checklist
Compare vs ZeroBouncevs NeverBouncevs Emailable Pricing comparedCredit expiry comparedAll comparisons
Resources GuidesBounce rate benchmarksHow many bounces burn a domain?MX records MX lookupDomain health reportEmail list cleanerAll MX Tools
Pricing
Home / Developers / Java

Email verification API for Java

Verify one address or a whole list from Java with the JDK's own HTTP client. Plain HTTPS and JSON, one bearer key, no SDK, and every example below compiles as written.

Updated 2026-11-24

Illustration for "Email verification API for Java"

TL;DR

  • The Mail Exchange API is plain HTTPS and JSON at https://mailexchange.com/api/v1. In Java you need java.net.http.HttpClient and a JSON library. No SDK.
  • POST /verify checks one address and usually answers in a few seconds. POST /lists takes up to 100,000 addresses per call and you poll for the result.
  • Branch on state: deliverable, risky, undeliverable or unknown. The decide() method below turns it into send, separate, skip, remove or retry.
  • Plan for three status codes: 202 (still checking), 402 (out of credits) and 429 (slow down).

Why a regex is not enough

Most "validate email in Java" answers stop at a regular expression or jakarta.mail.internet.InternetAddress. Both only check the format. [email protected] passes either test whether or not Acme still employs Jane, whether acme.com receives mail at all, or whether the domain accepts every address (a catch-all). Those are the cases that bounce.

An API check answers the other questions. Mail Exchange runs six checks per address: syntax, DNS and MX records, risk lists, an SMTP mailbox check, a catch-all test, then a verdict. It never sends an email. How it works walks through each one. Keep your regex as a free first filter, then send what passes to the API.

The share of addresses that need more than a format check is large. In Mail Exchange's checks of 779,784 unique business addresses across 200,799 domains (17 Oct to 22 Nov 2026), 7.6% were undeliverable and 18.1% were catch-all. The sample is mostly B2B contact lists processed through our API, not a random sample of all email. Only 100 of those addresses failed on syntax; almost every bad address looked fine to a format check.

Mail Exchange's checks of 779,784 unique business addresses across 200,799 domains, 17 Oct to 22 Nov 2026. Mostly B2B contact lists, not a random sample of all email. Almost all of these addresses had valid syntax.

Get an API key and set up the project

Sign up, then create a key in your account under API keys. Every request sends the key as Authorization: Bearer your_key. Keep it in an environment variable, as the examples do, and out of source control.

You need Java 17 or newer (the examples use records and switch expressions). HTTP uses java.net.http.HttpClient, part of the JDK since Java 11 per its Javadoc (checked 2026-11-22). The JDK has no JSON parser, so the examples add Jackson (com.fasterxml.jackson.core:jackson-databind, any current 2.x version).

Both objects are safe to share. Oracle's Javadoc says that "once built, an HttpClient is immutable, and can be used to send multiple requests", and Jackson's ObjectMapper documentation says instances are thread-safe if all configuration happens before the first read or write (both checked 2026-11-22). That is why each is a single static final field. In Spring Boot you can swap in RestClient or WebClient; the contract is just a bearer header and JSON.

Verify one address in Java

Save this as Verify.java. The call helper sends the key, retries on 429, and turns error responses into an exception carrying the API's message. verifyOne posts the address and handles the one tricky case: a slow mail server.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Map;

public class Verify {
    static final String BASE = "https://mailexchange.com/api/v1";
    static final ObjectMapper JSON = new ObjectMapper();       // thread-safe once configured
    static final HttpClient HTTP = HttpClient.newHttpClient(); // immutable, reuse it

    record Reply(int status, JsonNode body) {}

    static class MxException extends RuntimeException {
        final int status;

        MxException(int status, String message) {
            super("HTTP " + status + ": " + message);
            this.status = status;
        }
    }

    /** One API call. Retries 429 with exponential backoff, throws MxException on other errors. */
    static Reply call(String method, String path, Object body) throws Exception {
        String key = System.getenv("MAILEXCHANGE_API_KEY");
        for (int attempt = 0; ; attempt++) {
            HttpRequest.BodyPublisher publisher = body == null
                    ? HttpRequest.BodyPublishers.noBody()
                    : HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body));
            HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
                    .timeout(Duration.ofSeconds(45))
                    .header("Authorization", "Bearer " + key)
                    .header("Content-Type", "application/json")
                    .method(method, publisher)
                    .build();
            HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 429 && attempt < 4) {
                Thread.sleep(1000L << attempt);
                continue;
            }
            String text = response.body();
            JsonNode json = text.isBlank() ? JSON.createObjectNode() : JSON.readTree(text);
            if (response.statusCode() >= 400) {
                throw new MxException(response.statusCode(), json.path("error").asText(text));
            }
            return new Reply(response.statusCode(), json);
        }
    }

    /** Turn a result into an action: send, separate, skip, remove or retry. */
    static String decide(JsonNode result) {
        String reason = result.path("reason").asText();
        return switch (result.path("state").asText()) {
            case "deliverable" -> "send";
            case "risky" -> reason.equals("low_deliverability") ? "separate" : "skip"; // catch-all vs role/disposable
            case "undeliverable" -> "remove";
            default -> "retry"; // unknown, or still pending
        };
    }

    static JsonNode verifyOne(String email) throws Exception {
        Reply first = call("POST", "/verify", Map.of("email", email));
        if (first.status() != 202) {
            return first.body();
        }
        // 202: the mail server is slow. The check is running and already paid for.
        // Do not post the address again, poll the list instead.
        long listId = first.body().path("list_id").asLong();
        for (int i = 0; i < 36; i++) {
            Thread.sleep(5000);
            JsonNode rows = call("GET", "/lists/" + listId + "/results?limit=1", null).body().path("results");
            if (rows.size() > 0 && !rows.get(0).path("state").asText().equals("pending")) {
                return rows.get(0);
            }
        }
        return first.body(); // still pending after 3 minutes: look again later with the same list_id
    }

    public static void main(String[] args) throws Exception {
        try {
            JsonNode res = verifyOne(args[0]);
            System.out.println(res.path("email").asText() + " " + res.path("state").asText() + " "
                    + res.path("reason").asText() + " -> " + decide(res));
        } catch (MxException e) {
            System.err.println("Mail Exchange error: " + e.getMessage());
            System.exit(1);
        }
    }
}

Run it as a single source file:

CP="jackson-databind.jar:jackson-core.jar:jackson-annotations.jar"
MAILEXCHANGE_API_KEY=mx_live_xxx java -cp "$CP" Verify.java [email protected]

Typical output: [email protected] deliverable accepted_email -> send. With Maven or Gradle, add the Jackson dependency and run the class normally.

About the 202. If a mail server is slow, /verify waits about 20 seconds and then returns 202 with {"state": "pending", "list_id": ...}. That check is already running and already charged. Posting the same address again would start and charge a second check, so read the result from /lists/{list_id}/results, as the code does.
Most checks return 200 within a few seconds. After about 20 seconds a slow server gets 202 with a list_id: read the result from the list instead of sending the address again.

Read the result and decide what to do

A result is a flat JSON object: email, state, reason, score, the flags accept_all, role, free and disposable, plus mx. Branch on state. The reason tells you why, and it matters for the risky group.

statereasondecide() returnsWhy
deliverableaccepted_emailsendThe mail server accepted the mailbox.
riskylow_deliverabilityseparateCatch-all domain. The server accepts any address, so the mailbox can't be confirmed.
riskylow_quality, disposableskipRole address (info@, sales@) or a throwaway domain.
undeliverablerejected_email, invalid_domain, invalid_emailremoveWill bounce. Drop it.
unknownunavailable_smtp, no_connect, dns_errorretryNo clear answer from the server. The credit is refunded.

The method is deliberately small so you can change it. A cold email team might send separate addresses only from established inboxes, as described in catch-all emails and cold email. A signup form might accept risky addresses and block only undeliverable ones. The full list is in email verification statuses.

Verify a list in Java

For more than a handful of addresses, submit one list instead of looping over /verify. You get a list ID straight away. Poll GET /lists/{id} until status is done (or failed), then page through /lists/{id}/results 1,000 rows at a time. Duplicates inside the list are removed and not charged. Save this as VerifyList.java next to Verify.java, with one address per line in emails.txt.

import com.fasterxml.jackson.databind.JsonNode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/** Reuses Verify.call and Verify.decide from Verify.java in the same folder. */
public class VerifyList {
    public static void main(String[] args) throws Exception {
        try {
            List<String> emails = Files.readAllLines(Path.of(args[0])).stream()
                    .map(String::trim).filter(s -> !s.isEmpty()).toList();
            JsonNode created = Verify.call("POST", "/lists", Map.of("emails", emails, "name", "java-example")).body();
            long id = created.path("id").asLong();

            JsonNode summary;
            while (true) {
                summary = Verify.call("GET", "/lists/" + id, null).body();
                String status = summary.path("status").asText();
                System.out.printf("%d/%d checked (%s)%n",
                        summary.path("checked").asInt(), summary.path("total").asInt(), status);
                if (status.equals("done") || status.equals("failed")) {
                    break;
                }
                Thread.sleep(5000);
            }
            if (summary.path("status").asText().equals("failed")) {
                throw new IllegalStateException("list " + id + " failed");
            }

            Map<String, Integer> actions = new TreeMap<>();
            for (int offset = 0; ; offset += 1000) {
                JsonNode rows = Verify.call("GET", "/lists/" + id + "/results?offset=" + offset + "&limit=1000", null)
                        .body().path("results");
                for (JsonNode row : rows) {
                    actions.merge(Verify.decide(row), 1, Integer::sum);
                }
                if (rows.size() < 1000) {
                    break;
                }
            }
            System.out.println("counts: " + summary.path("counts") + " actions: " + actions);

            Verify.call("DELETE", "/lists/" + id, null); // optional: remove the list and its results
        } catch (Verify.MxException e) {
            System.err.println("Mail Exchange error: " + e.getMessage());
            System.exit(1);
        }
    }
}
javac -cp "$CP" Verify.java VerifyList.java
MAILEXCHANGE_API_KEY=mx_live_xxx java -cp "$CP:." VerifyList emails.txt

Instead of polling you can pass a callback_url and we POST to it when the list is done; see webhooks and callbacks. CSV download and deletion are in verify a list with the API.

Duplicates in the list are removed and not charged, and unknown results are refunded when the list finishes. A callback_url can replace the polling loop.

Errors, 402 and 429

Every error response is JSON with an error field, which the helper puts in the exception message. The ones to plan for:

  • 429: you hit the per-key rate limit. The helper waits 1, 2, 4 and 8 seconds and tries again. That is safe because a rate-limited request does no work and costs nothing.
  • 402: not enough credits for the request. Retrying won't help. Stop, alert someone, and upgrade your plan or wait for it to renew. GET /account returns your balance if you want to check first.
  • 401: the key is missing or wrong. 400: the request was malformed, for example no email, or a list over 100,000 addresses.

A status code table is in errors, credits and rate limits.

What it costs

Each unique address costs one credit, charged when you submit it. Duplicates aren't charged and unknown results are refunded when the list finishes. Verifications reset every month, and unused ones don't carry over. A Java service that checks 10,000 new signups a month fits the Starter plan ($49 a month for 10,000 verifications, $0.0049 each at full use); a 100,000-row cleanup fits one month of the Agency plan ($249 a month for 100,000, $0.00249 each at full use). Every plan includes the API. All plans are on the pricing page, and the cost calculator prices your own volume.

Before you write any code, you can try the same checks on a few addresses in the browser with the free trial (25 checks) or the email checker.

FAQ

Is there an official Java SDK for the Mail Exchange API?

No, and none is needed. The API is plain HTTPS and JSON, so the examples on this page use only java.net.http.HttpClient from the JDK plus Jackson for JSON.

How do I verify an email address in Java?

Send POST https://mailexchange.com/api/v1/verify with a JSON body like {"email": "[email protected]"} and your key in an Authorization: Bearer header, using java.net.http.HttpClient. Read the state field in the response: deliverable, risky, undeliverable or unknown.

Can I verify email addresses in Java with a regex alone?

A regex only checks the format. It cannot tell you whether the domain accepts mail or whether the mailbox exists, which is what causes bounces. Use a regex as a cheap first filter and an API check for the rest.

How do I get an API key?

Sign up, then create a key in your account under API keys. Send the key as a bearer token in the Authorization header.

What should I do when /verify returns 202?

Do not send the address again. The check is already running and paid for. Read the result from /lists/{list_id}/results using the list_id in the 202 response, until the state is no longer pending.

Start your free trial →