What we'll build
A regular expression or Bean Validation's @Email can tell you an address looks right. Neither can tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build an EmailValidator.validate() method in Java that checks all of those and returns one of four statuses:
| Status | Meaning | Typical action |
|---|---|---|
valid | Well formed, and the domain accepts mail | Accept |
invalid | Bad syntax, no such domain, or no mail server | Reject and ask the user to fix it |
risky | Disposable, a likely typo, a role account, or no MX records | Your call: block, warn, or flag |
unknown | DNS failed temporarily | Accept and check again later |
You'll need Java 21 or later. Steps 1 to 6 use only the JDK: DNS lookups go through its built-in JNDI DNS provider, so there's nothing to add to your build. Step 7 uses Spring Boot with the web and validation starters:
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-validation'Every snippet was tested with Java 21 and Spring Boot 4.0. Want to see the end result first? The free email checker runs the same checks.
1. Check the syntax
Start with the check that needs no network. Instead of one huge regular expression, split the address at the last @ and check each part separately. The rules stay readable, and you can say exactly what's wrong:
package com.example.emailcheck;
import java.net.IDN;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.regex.Pattern;
public final class Syntax {
// RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
private static final Pattern ATOM = Pattern.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+");
// A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
private static final Pattern LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?");
public record Result(boolean ok, String reason, String local, String domain, String normalized) {
static Result fail(String reason) { return new Result(false, reason, null, null, null); }
}
/** Lower-cases a domain and converts international names to punycode, or returns null. */
static String toAsciiDomain(String domain) {
try {
return IDN.toASCII(domain.strip().replaceAll("\\.$", ""), IDN.USE_STD3_ASCII_RULES).toLowerCase(Locale.ROOT);
} catch (IllegalArgumentException e) {
return null;
}
}
public static Result check(String input) {
String email = input == null ? "" : input.strip();
if (email.length() > 254) return Result.fail("too_long");
int at = email.lastIndexOf('@');
if (at <= 0 || at == email.length() - 1) return Result.fail("missing_at_or_part");
String local = email.substring(0, at);
if (local.getBytes(StandardCharsets.UTF_8).length > 64) return Result.fail("local_part_too_long");
// split(…, -1) keeps empty parts, so leading, trailing and doubled dots fail.
for (String atom : local.split("\\.", -1)) {
if (!ATOM.matcher(atom).matches()) return Result.fail("invalid_local_part");
}
String domain = toAsciiDomain(email.substring(at + 1));
String[] labels = domain == null ? new String[0] : domain.split("\\.", -1);
if (labels.length < 2 || labels[labels.length - 1].matches("\\d+")) return Result.fail("invalid_domain");
for (String label : labels) {
if (!LABEL.matcher(label).matches()) return Result.fail("invalid_domain");
}
return new Result(true, null, local, domain, local.toLowerCase(Locale.ROOT) + "@" + domain);
}
}Notes on the code:
IDN.toASCII()converts international domains to punycode (münchen.debecomesxn--mnchen-3ya.de), which is the form DNS needs. WithUSE_STD3_ASCII_RULESit also rejects characters that can't appear in a host name.split("\\.", -1)keeps empty parts, so.jane,jane.andja..neall fail with no extra rules. Without the-1, Java drops trailing empty parts andjane.would pass.matcher().matches()must match the whole string, so the patterns need no^or$.- The local part limit is 64 bytes (RFC 5321), so the length is measured in UTF-8 bytes, not
length().
Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.
2. Check the domain's MX records
A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail.
InetAddress can only look up addresses, not MX records. The JDK's JNDI DNS provider can, and it reports a missing domain with NameNotFoundException, separately from DNS trouble, so each case gets the right status:
package com.example.emailcheck;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.InitialDirContext;
public final class DnsCheck {
public record Result(String status, String reason, List<String> mx) {}
/** "dns:" uses the system's DNS servers; tests can point it at "dns://127.0.0.1:5353". */
static String dnsUrl = "dns:";
private static InitialDirContext context() throws NamingException {
var env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, dnsUrl);
// A short timeout (1 s, then 2 s), so a slow DNS server can't stall a sign-up.
env.put("com.sun.jndi.dns.timeout.initial", "1000");
env.put("com.sun.jndi.dns.timeout.retries", "2");
return new InitialDirContext(env);
}
/** The records of one type, or null when the domain exists but has none. */
private static Attribute lookup(InitialDirContext ctx, String domain, String type) throws NamingException {
// The trailing dot stops the resolver from trying "domain.your-search-domain" too.
return ctx.getAttributes(domain + ".", new String[] {type}).get(type);
}
public static Result check(String domain) {
try {
var ctx = context();
Attribute mx;
try {
mx = lookup(ctx, domain, "MX");
} catch (NameNotFoundException e) {
return new Result("invalid", "domain_not_found", List.of());
}
if (mx != null) {
// Each value looks like "10 mx.example.com.".
List<String[]> records = Collections.list(mx.getAll()).stream()
.map(v -> v.toString().split(" ", 2))
.sorted(Comparator.comparingInt(r -> Integer.parseInt(r[0])))
.toList();
// RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
if (records.size() == 1 && records.get(0)[1].equals(".")) {
return new Result("invalid", "domain_rejects_mail", List.of());
}
return new Result("ok", null, records.stream().map(r -> r[1].replaceAll("\\.$", "")).toList());
}
// No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
boolean hasAddress = lookup(ctx, domain, "A") != null || lookup(ctx, domain, "AAAA") != null;
return hasAddress
? new Result("risky", "no_mx_records", List.of())
: new Result("invalid", "no_mail_server", List.of());
} catch (NamingException e) {
// SERVFAIL, timeouts and other DNS trouble are temporary. Don't blame the user.
return new Result("unknown", "dns_error", List.of());
}
}
}| Result | Meaning | Status |
|---|---|---|
| MX records returned | The domain accepts mail | ok |
| One MX record with an empty name | "Null MX" (RFC 7505): the domain accepts no mail | invalid |
NameNotFoundException | The domain doesn't exist | invalid |
No MX attribute in the answer | The domain exists but has no MX records, so check A/AAAA | risky or invalid |
Any other NamingException | SERVFAIL or a timeout: DNS trouble, not the user's fault | unknown |
Keep the timeout short, so a slow DNS server can't hold up a sign-up, and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment. If you'd rather use a library, dnsjava exposes the same response codes.
3. Cache DNS lookups
Most of your users share a handful of domains like gmail.com and outlook.com. A Java server handles many requests in one process, so a shared map saves most lookups:
package com.example.emailcheck;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class DnsCache {
private record Entry(DnsCheck.Result result, Instant expires) {}
private static final Duration TTL = Duration.ofHours(1);
private static final Map<String, Entry> CACHE = new ConcurrentHashMap<>();
public static DnsCheck.Result check(String domain) {
Entry hit = CACHE.get(domain);
if (hit != null && hit.expires().isAfter(Instant.now())) return hit.result();
DnsCheck.Result result = DnsCheck.check(domain);
// Don't remember temporary failures.
if (!result.status().equals("unknown")) CACHE.put(domain, new Entry(result, Instant.now().plus(TTL)));
return result;
}
}ConcurrentHashMap is safe to use from every request thread at once. If you already use Caffeine or Spring's cache abstraction, use that with the same one-hour expiry instead. Either way, don't cache failed lookups.
4. Detect disposable domains
Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list to your app's working directory:
curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.confpackage com.example.emailcheck;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.stream.Collectors;
public final class Disposable {
// One domain per line, loaded once. A Set makes each lookup instant.
private static final Set<String> BLOCKLIST = load(Path.of("disposable_email_blocklist.conf"));
private static Set<String> load(Path file) {
try (var lines = Files.lines(file)) {
return lines.map(String::strip).filter(l -> !l.isEmpty()).collect(Collectors.toUnmodifiableSet());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com". */
public static boolean isDisposable(String domain) {
String[] labels = domain.split("\\.");
for (int i = 0; i < labels.length - 1; i++) {
if (BLOCKLIST.contains(String.join(".", java.util.Arrays.copyOfRange(labels, i, labels.length)))) return true;
}
return false;
}
}Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job and restart, or load it from the classpath if you'd rather ship it inside your jar.
The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a didYouMean suggestion for a disposable address. Read more about how disposable email detection works.
5. Flag role accounts and suggest typo fixes
Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:
package com.example.emailcheck;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public final class Extras {
private static final Set<String> ROLE_ACCOUNTS = Set.of(
"admin", "billing", "contact", "help", "hello", "info", "marketing", "no-reply",
"noreply", "office", "postmaster", "sales", "support", "team", "webmaster");
public static boolean isRoleAccount(String local) {
// Ignore "+tag" sub-addressing: "support+billing" is still "support".
return ROLE_ACCOUNTS.contains(local.toLowerCase(Locale.ROOT).split("\\+", 2)[0]);
}
// Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
// too, or they'd be "corrected" to the provider one letter away.
private static final List<String> POPULAR_DOMAINS = List.of(
"gmail.com", "googlemail.com", "yahoo.com", "ymail.com", "yahoo.co.uk", "hotmail.com",
"hotmail.co.uk", "outlook.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com",
"aol.com", "mail.com", "gmx.com", "gmx.de", "proton.me", "protonmail.com");
/** Levenshtein distance: the number of single-character edits between two strings. */
static int editDistance(String a, String b) {
int[] prev = new int[b.length() + 1];
for (int j = 0; j <= b.length(); j++) prev[j] = j;
for (int i = 1; i <= a.length(); i++) {
int[] row = new int[b.length() + 1];
row[0] = i;
for (int j = 1; j <= b.length(); j++) {
int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
row[j] = Math.min(Math.min(prev[j] + 1, row[j - 1] + 1), prev[j - 1] + cost);
}
prev = row;
}
return prev[b.length()];
}
/** "gmial.com" → "gmail.com"; null when the domain is fine or nothing is close. */
public static String suggestDomain(String domain) {
if (POPULAR_DOMAINS.contains(domain)) return null;
String best = null;
int bestDistance = Integer.MAX_VALUE;
for (String candidate : POPULAR_DOMAINS) {
int d = editDistance(domain, candidate);
if (d < bestDistance) {
best = candidate;
bestDistance = d;
}
}
// Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
return bestDistance <= (domain.length() <= 6 ? 1 : 2) ? best : null;
}
}The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain.
Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.
6. Put it together
Now run the checks from cheapest to most expensive and return a single verdict:
package com.example.emailcheck;
public final class EmailValidator {
/** status is "valid", "invalid", "risky" or "unknown". */
public record Verdict(String status, String reason, String email, String didYouMean) {}
public static Verdict validate(String input) {
Syntax.Result syntax = Syntax.check(input);
if (!syntax.ok()) return new Verdict("invalid", syntax.reason(), null, null);
String local = syntax.local(), domain = syntax.domain();
String suggestion = Extras.suggestDomain(domain);
String didYouMean = suggestion == null ? null : local + "@" + suggestion;
DnsCheck.Result dns = DnsCache.check(domain);
if (dns.status().equals("invalid") || dns.status().equals("unknown")) {
return new Verdict(dns.status(), dns.reason(), syntax.normalized(), didYouMean);
}
// The domain can receive mail. Now look for risk signals, most serious first.
String reason = Disposable.isDisposable(domain) ? "disposable"
: suggestion != null ? "possible_typo"
: dns.status().equals("risky") ? dns.reason()
: Extras.isRoleAccount(local) ? "role_based"
: null;
return reason == null
? new Verdict("valid", "mail_server_found", syntax.normalized(), didYouMean)
: new Verdict("risky", reason, syntax.normalized(), didYouMean);
}
}It returns these results for a range of inputs:
| Input | status | reason | didYouMean |
|---|---|---|---|
jane@gmail.com | valid | mail_server_found | null |
joe@gamil.com | risky | possible_typo | joe@gmail.com |
test@mailinator.com | risky | disposable | null |
support@acme.io | risky | role_based | null |
x@no-such-domain.example | invalid | domain_not_found | null |
not-an-email | invalid | missing_at_or_part | null |
7. Use it in Spring Boot
A typical sign-up policy is to reject invalid and disposable addresses and accept everything else. Bean Validation's @Email covers step 1 only, so add a custom constraint for the rest:
package com.example.emailcheck;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** Rejects addresses that can't receive mail and disposable inboxes. Use next to @Email. */
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Deliverable.Validator.class)
public @interface Deliverable {
String message() default "must be a working, permanent email address";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class Validator implements ConstraintValidator<Deliverable, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) return true; // leave missing values to @NotBlank
var result = EmailValidator.validate(value);
return !result.status().equals("invalid") && !"disposable".equals(result.reason());
}
}
}Then use it on the request body next to @Email:
package com.example.emailcheck;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
@RestController
public class SignupController {
public record SignupRequest(@NotBlank @Email @Deliverable String email) {}
@PostMapping("/signup")
public ResponseEntity<Map<String, Object>> signup(@Valid @RequestBody SignupRequest request) {
var result = EmailValidator.validate(request.email()); // cached: no second DNS lookup
// "unknown" means DNS had a hiccup. Accept the address and check it again later.
// userService.create(result.email());
return ResponseEntity.status(HttpStatus.CREATED)
.body(Map.of("ok", true, "email", result.email(), "didYouMean", String.valueOf(result.didYouMean())));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_CONTENT)
public Map<String, String> invalid(MethodArgumentNotValidException e) {
return Map.of("error", "Please use a working, permanent email address.");
}
}Spring runs the validator before the controller method, and the @ExceptionHandler turns a failed check into a 422 response. The second validate() call in the controller is cheap, because the domain is already cached. Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.
8. Test it
The syntax check has no side effects, so a JUnit 5 parameterized test covers it:
package com.example.emailcheck;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class SyntaxTest {
@ParameterizedTest
@ValueSource(strings = {"jane@example.com", "jane.doe+news@example.co.uk", "user@münchen.de"})
void acceptsNormalAddresses(String email) {
assertTrue(Syntax.check(email).ok());
}
@ParameterizedTest
@ValueSource(strings = {"", "jane", "@example.com", "jane@", "a..b@example.com", "jane@example", "jane@-example.com"})
void rejectsMalformedAddresses(String email) {
assertFalse(Syntax.check(email).ok());
}
}For the DNS checks, point JNDI at a local test DNS server by setting the provider URL to dns://127.0.0.1:5353. Then your test suite doesn't depend on the internet. That's how we tested every result on this page, including the Spring Boot endpoint with MockMvc.
What about checking that the mailbox exists?
You could go further with a socket: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.
For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.
Or use an email validation API
Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request, here with the JDK's HttpClient and the Jackson 3 that Spring Boot 4 includes:
package com.example.emailcheck;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
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.ArrayList;
import java.util.List;
import java.util.Map;
public final class ApiClient {
private static final String API = "https://validateemail.io/v1";
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
private static final JsonMapper JSON = JsonMapper.builder().build();
private static JsonNode post(String path, Object body, Duration timeout) throws Exception {
var request = HttpRequest.newBuilder(URI.create(API + path))
.timeout(timeout)
.header("Authorization", "Bearer " + System.getenv("VALIDATEEMAIL_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
.build();
var response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) throw new IllegalStateException("HTTP " + response.statusCode());
return JSON.readTree(response.body());
}
public static JsonNode validate(String email) {
try {
return post("/validate", Map.of("email", email), Duration.ofSeconds(5));
} catch (Exception e) {
// Never block a sign-up because the validator is slow or unreachable.
System.getLogger("email").log(System.Logger.Level.WARNING, "Email validation unavailable: " + e);
return JSON.valueToTree(Map.of("status", "unknown", "reason", "validator_unavailable"));
}
}
/** Validates any number of addresses, 100 per request. */
public static List<JsonNode> validateList(List<String> emails) throws Exception {
var results = new ArrayList<JsonNode>();
for (int i = 0; i < emails.size(); i += 100) {
var page = post("/validate/batch", Map.of("emails", emails.subList(i, Math.min(i + 100, emails.size()))), Duration.ofSeconds(30));
page.get("results").forEach(results::add);
}
return results;
}
}If the API is slow or unreachable, ApiClient.validate() returns unknown instead of throwing, so a network problem never blocks a sign-up. The response has the same status and reason fields used in this guide (as did_you_mean rather than didYouMean), plus a score and the result of every individual check.
Using an AI coding assistant? Paste this prompt and it will wire up the API for you:
Add email validation to the sign-up endpoint of this Java Spring Boot app using the validateemail.io API (reference: https://validateemail.io/llms.txt).
- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.Frequently asked questions
Is @Email enough to validate an email in Spring Boot?
@Email is a format check. It can't tell you whether the domain exists or accepts mail, or whether the address is disposable or mistyped, so pair it with a custom constraint like @Deliverable in step 7, which adds the MX lookup and the other checks.
How do I look up MX records in Java without a library?
Use the JDK's JNDI DNS provider: create an InitialDirContext with com.sun.jndi.dns.DnsContextFactory and call getAttributes(domain, new String[] {"MX"}). A NameNotFoundException means the domain doesn't exist; other NamingExceptions are temporary DNS problems.
Does Apache Commons EmailValidator check the domain?
No. Commons Validator's EmailValidator checks the format and that the top-level domain is real. It doesn't look up DNS, so a domain that doesn't exist or has no mail server still passes.
Can Java check that a mailbox exists without sending an email?
You can try by opening a socket to the domain's mail server on port 25 and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.