# Validate email addresses with Java

The ValidatedMails API evaluates syntax, DNS routing, and SMTP acceptance for a single address. Each response returns a normalized verdict state plus supporting signals for consistent application behavior.

Response contract:

every request returns a four-state

status

, a numeric

score

, and a

trace_id

for correlation.

## Overview

The `/validate` endpoint evaluates email syntax, DNS routing, and SMTP acceptance for a single address. The response represents a normalized verdict state plus supporting signals for consistent application logic.

## Quickstart

Call `/validate` with a `GET` request using query parameters, or a `POST` request with a JSON body. Both return the same response payload.

```java
GET https://api.validatedmails.com/validate/?email=ada@acme.com&token=YOUR_API_TOKEN
```

```java
POST https://api.validatedmails.com/validate?token=YOUR_API_TOKEN
Content-Type: application/json

{
  "email": "ada@acme.com"
}
```

The response includes the four-state `status`, a boolean convenience field (`is_valid`), a numeric `score`, and a `trace_id` for correlation.

## Java example (HttpClient)

Use the Java 11+ `HttpClient` with a simple JSON parser. The example below shows both `GET` and `POST` request styles and a minimal response handler.

```java
import java.io.IOException;
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.net.http.HttpTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import org.json.JSONObject;

public class ValidateEmail {
    private static final String API_BASE_URL =
        System.getenv().getOrDefault("VALIDATEDMAILS_API_BASE_URL", "https://api.validatedmails.com");
    private static final String API_TOKEN =
        System.getenv().getOrDefault("VALIDATEDMAILS_API_TOKEN", "YOUR_API_TOKEN");

    private static final HttpClient CLIENT = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build();

    public static JSONObject validateGet(String email) throws IOException, InterruptedException {
        String encodedEmail = URLEncoder.encode(email, StandardCharsets.UTF_8);
        String uri = String.format("%s/validate/?email=%s&token=%s", API_BASE_URL, encodedEmail, API_TOKEN);

        HttpRequest request = HttpRequest.newBuilder(URI.create(uri))
            .timeout(Duration.ofSeconds(10))
            .header("Accept", "application/json")
            .GET()
            .build();

        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() / 100 != 2) {
            throw new IOException("ValidatedMails API error: HTTP " + response.statusCode() + " - " + response.body());
        }
        return new JSONObject(response.body());
    }

    public static JSONObject validatePost(String email) throws IOException, InterruptedException {
        String uri = String.format("%s/validate?token=%s", API_BASE_URL, API_TOKEN);
        JSONObject payload = new JSONObject().put("email", email);

        HttpRequest request = HttpRequest.newBuilder(URI.create(uri))
            .timeout(Duration.ofSeconds(10))
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload.toString()))
            .build();

        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() / 100 != 2) {
            throw new IOException("ValidatedMails API error: HTTP " + response.statusCode() + " - " + response.body());
        }
        return new JSONObject(response.body());
    }

    public static void main(String[] args) {
        try {
            JSONObject result = validateGet("ada@acme.com");
            String status = result.getString("status");
            boolean isValid = result.getBoolean("is_valid");
            int score = result.getInt("score");
            String traceId = result.getString("trace_id");

            System.out.println("status: " + status);
            System.out.println("is_valid: " + isValid);
            System.out.println("score: " + score);
            System.out.println("trace_id: " + traceId);

            if ("valid".equals(status)) {
                System.out.println("Accept signup");
            } else if ("invalid".equals(status)) {
                System.out.println("Reject signup");
            } else {
                System.out.println("Risky or unknown: apply your review or confirmation policy");
            }
        } catch (HttpTimeoutException e) {
            System.err.println("ValidatedMails API timeout: " + e.getMessage());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("ValidatedMails API interrupted: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("ValidatedMails API error: " + e.getMessage());
        }
    }
}
```

Sample response payload:

```json
{
  "is_valid": true,
  "status": "valid",
  "score": 95,
  "smtp_ok": true,
  "accept_all": false,
  "disposable": false,
  "role": false,
  "free": false,
  "tag": false,
  "mx_ok": true,
  "a_ok": true,
  "trace_id": "..."
}
```

## Response usage

### valid

Accept the address and proceed with standard onboarding flows. The result indicates syntax, routing, and SMTP checks passed.

### invalid

Reject the address immediately or ask for an alternative. The result indicates the address failed validation or was explicitly rejected by SMTP.

### unknown

Treat the address as unverified and route to your confirmation or review policy. The result indicates insufficient evidence to decide.

## Error handling + timeouts

- Set explicit connect and request timeouts to align with your application latency budget.
- Retry temporary failures such as HTTP `429`, HTTP `5xx`, network errors, and client timeouts with bounded backoff. Honor`Retry-After` when it is present.
- Capture `trace_id` from every response to correlate logs and support cases.

## Common integration patterns

### Server-side signup flow

- Validate before creating the account.
- Allow `valid` to continue without friction.
- Escalate `unknown` to confirmation or manual review.

### Background job / batch validation

- Use `POST /validate/batch` for queued lists and worker jobs.
- Submit full batches where possible and keep explicit client timeouts.
- Run parallel batch workers to reach your target throughput.
- Use Bulk validation jobs for very large CSV imports and full-list processing.
- Log non-2xx response bodies for diagnosis.
- Store `status`, `score`, and `trace_id` for auditability.
- Recheck `unknown` in a later pass if needed.
