Real-time email verification using the modern java.net.http.HttpClient
introduced in Java 11.
This tutorial parses the response with org.json. Any JSON library (Jackson, Gson) works the same way.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
Send a GET request with the email and your API token, and check the HTTP status before reading the result.
The helper below returns one of three decisions: accept, reject or defer.
Running out of credits (402), a rate limit (429), an outage or an Unknown result
never becomes a rejection, and a temporary Unknown is asked again after RetryAfterSeconds.
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.json.JSONObject;
public class EmailVerifier {
private static final String API_URL = "https://api.validemail.net/";
private static final String API_KEY = "YOUR_API_KEY"; // find it in your ValidEmail dashboard; keep it on your server
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
/** decision is "accept", "reject" or "defer". */
record Verdict(String decision, String reason) {}
public static void main(String[] args) throws Exception {
Verdict verdict = verifyEmail("someone@example.com", 3);
System.out.println(verdict.decision() + ": " + verdict.reason());
}
// "defer" means: let the user continue, keep the address flagged, check it again later.
// Running out of credits, a rate limit or an outage never turns into "reject".
static Verdict verifyEmail(String email, int maxAttempts) throws InterruptedException {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
String url = API_URL + "?email=" + URLEncoder.encode(email, StandardCharsets.UTF_8)
+ "&token=" + API_KEY;
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(90))
.GET()
.build();
HttpResponse<String> response;
try {
response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
} catch (java.io.IOException e) {
return new Verdict("defer", "network: " + e.getMessage());
}
// 1. The HTTP status first: only a 200 carries a verdict about the address.
int status = response.statusCode();
if (status == 402) {
System.err.println("ValidEmail is out of credits. " + response.body()); // alert whoever pays the bill
return new Verdict("defer", "no_credits");
}
if (status == 429) {
long wait = response.headers().firstValueAsLong("Retry-After").orElse(1);
Thread.sleep(Math.max(1, wait) * 1000L);
continue;
}
if (status != 200) {
return new Verdict("defer", "http_" + status);
}
// 2. Then the verdict.
JSONObject result = new JSONObject(response.body());
String state = result.getString("State");
String reason = result.optString("Reason", "");
if ("Deliverable".equals(state)) return new Verdict("accept", reason);
if ("Not Deliverable".equals(state)) return new Verdict("reject", reason);
int retryAfter = result.optInt("RetryAfterSeconds", 0);
if (retryAfter > 0) {
// Still being resolved (greylisting, a slow server). Asking again for the same address is free.
Thread.sleep(retryAfter * 1000L);
continue;
}
return new Verdict("defer", reason); // Unknown, and no answer is coming
}
return new Verdict("defer", "still pending");
}
}
State = "Unknown")
Some mail servers greylist first-time senders or respond slowly. Instead of failing, the API returns an
interim 200 OK result with State = "Unknown", a Reason of
PENDING or GREYLISTED, and a RetryAfterSeconds hint while the
verification finishes in the background.
RetryAfterSeconds seconds, then repeat the same request to get the final verdict.Unknown as "not yet decided" — never as a delivery failure.The balance endpoint is free to call and never consumes a credit — perfect for a pre-flight check before verifying a large list.
HttpRequest balanceRequest = HttpRequest.newBuilder(
URI.create("https://api.validemail.net/balance?token=" + API_KEY))
.GET()
.build();
HttpResponse<String> balanceResponse = CLIENT.send(balanceRequest, HttpResponse.BodyHandlers.ofString());
int balance = new JSONObject(balanceResponse.body()).getInt("balance");
System.out.println("Credits remaining: " + balance);
| HTTP Status | Meaning | What to do |
|---|---|---|
| 200 OK | The request was processed. Check State — a result with State = "Unknown" and a RetryAfterSeconds value is an interim answer, not a final verdict. |
Use the result. If State is Unknown, retry the same request after RetryAfterSeconds. |
| 400 Bad Request | Missing email/token parameter, or a transient processing failure. |
Check the response text and retry. |
| 402 Payment Required | No credits remaining. The JSON body says what is missing and what fixes it: {"error":"no_credits","shortfall":1,"pack":{"credits":5000,"price":9.50,"currency":"USD"},"buyUrl":"https://validemail.net/BuyCredits?credits=5000","message":"…"}. |
Stop sending requests, open buyUrl to top up (the pack is preselected), then retry. Need an invoice or a larger volume? Email info@validemail.net. |
| 401 Unauthorized | The API key is invalid or unknown. | Verify the token value against the API key shown in your dashboard. |
| 403 Forbidden | The account attached to this API key is inactive. | Contact info@validemail.net to reactivate the account. |
| 429 Too Many Requests | You exceeded your per-second request limit. The response body includes the configured limit. | Slow down and retry with backoff, or contact us to raise your rate limit. |
Explore every response field and status code in the full API reference.
Hi. I'm ValidEmail's AI assistant. Ask me about verifying a list, the API, prices or your account.