Guides
Last updated
July 20, 2025

5 Ways to Implement Email Validation in Java

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating email addresses in Java is a common requirement for ensuring data quality and preventing user input errors. We will explore five ways to handle this, providing working code for each method. We'll also examine the pitfalls of traditional approaches and see how Abstract API helps overcome them.

How to Implement Email Validation in Java

Here are four common methods for email validation in Java. Each approach has a different implementation, from simple pattern matching to checks that involve network requests for domain verification.

Regex with java.util.regex.Pattern

This technique uses a regular expression to match an email string against a defined pattern. The `java.util.regex.Pattern` class compiles the expression once for efficiency, and this pre-compiled pattern can be reused. The `matcher` method then attempts to match the candidate email, returning a boolean result. The provided Baeldung article explains this pattern covers most standard cases.

private static final Pattern EMAIL = Pattern.compile("^[A-Za-z0-9_+&*-]+(?:\\.[A-Za-z0-9_+&*-]+)*@(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,7}$");
boolean ok = EMAIL.matcher(candidate).matches();

The javax.mail.internet.InternetAddress Class

You can use the parser built into the JavaMail API. This approach involves creating a new "InternetAddress" object with the candidate email string. The constructor and the "validate" method work together to enforce email syntax rules.

If the address is invalid, the code throws an "AddressException", which you can catch to handle the failure. According to Oracle's documentation, this method enforces most RFC 822 and 5322 rules without complex regular expressions and is not dependent on the system's locale.

boolean ok;
try {
    new InternetAddress(candidate).validate();
    ok = true;
} catch (AddressException ex) {
    ok = false;
}

The Apache Commons Validator

For this method, you add the `commons-validator` library to your project. The library provides a dedicated `EmailValidator` class. You get an instance of the validator and then use its `isValid` method to check the email string. The official documentation shows this validator is highly configurable, with support for Internationalized Domain Names and a small runtime footprint.

EmailValidator v = EmailValidator.getInstance(false, false);
boolean ok = v.isValid(candidate);

Syntax Check with DNS MX Lookup

This is a multi-step process that combines syntax validation with a network check. First, you perform a lightweight pattern check using a method like regex or the Apache Commons Validator.

After the syntax passes, you query the Domain Name System (DNS) to confirm the email's domain has a Mail Exchange (MX) record. This check confirms the domain is configured to accept email.

This approach helps filter out emails that are syntactically correct but belong to a domain that cannot receive mail, as this blog post explains. The code extracts the domain and uses a directory context to request its "MX" attributes. A positive result indicates the domain can receive mail.

String domain = candidate.substring(candidate.indexOf('@') + 1);
DirContext ctx = new InitialDirContext();
Attributes mx = ctx.getAttributes("dns:/" + domain, new String[]{"MX"});
boolean ok = mx.size() > 0;

Challenges of Implementing Email Validation in Java

Traditional Java email validation methods often seem straightforward but conceal significant complexities. These approaches struggle with modern email standards, deliverability checks, and numerous edge cases that lead to unreliable results.

  • The official email grammar includes features like quoted strings and comments. Methods like java.util.regex.Pattern and InternetAddress cannot express this full complexity, which results in either overly complex or incomplete validators that fail on valid addresses.
  • International emails with Unicode characters present a major hurdle. Legacy code and many validators, including older versions of JavaMail, fail to handle these addresses correctly. This leads to false negatives for a growing number of global users.
  • A syntactically correct email does not guarantee deliverability. While a DNS MX lookup can check the domain, it introduces network latency and complex error states. Most simple syntax checks completely ignore if the domain can actually receive mail.
  • Common regex patterns often reject valid edge cases like domains with leading hyphens or case-sensitive local parts. Attempts to fix this can loosen the rules too much, which then accepts invalid formats and creates a cycle of false results.

Validate Emails with Abstract API
Protect your Java project from bad data by validating email addresses for improved data quality.
Get started for free

How Abstract API Handles Email Validation in Java

Abstract API addresses the core weaknesses of traditional validation methods by the replacement of complex local checks with a single HTTPS call.

  • It chains multiple checks, from format validation and typo correction to MX and live SMTP tests.
  • The API detects disposable, role-based, and catch-all addresses through its internal heuristics.
  • All complex logic, block-lists, and typo tables reside on Abstract’s servers, so your code only parses a final JSON payload.

How to Set Up Abstract API in Your Project

Once you're familiar with Abstract’s capabilities, the process to add its email validation API to your project is simple.

  • Sign in at Abstract API, enable “Email Verification & Validation,” and copy your API key.
  • Ensure you have Java 11 or newer. For older JDKs, add OkHttp and a JSON library to your build.
  • Store the API key as "EMAIL_API_KEY" in your secret manager or as an environment variable.
  • Inject HttpClient or OkHttp into the component that handles user-supplied email addresses.
  • Construct the request URL: https://emailvalidation.abstractapi.com/v1/?api_key=KEY&email=EMAIL.
  • Parse the JSON response and interrupt your registration flow if the deliverability is not “DELIVERABLE”.
HttpClient client = HttpClient.newHttpClient();
String url = String.format("https://emailvalidation.abstractapi.com/v1/?api_key=%s&email=%s", System.getenv("EMAIL_API_KEY"), URLEncoder.encode(email, StandardCharsets.UTF_8));
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
ObjectNode json = new ObjectMapper().readValue(res.body(), ObjectNode.class);
if (!"DELIVERABLE".equals(json.path("deliverability").asText())) { throw new IllegalArgumentException("Invalid email"); }

Sample Email Validation Implementation with Abstract API

The Java code sends a GET request to Abstract API with your key and the user's email. It then parses the JSON response to check the "deliverability" field. If the status is not "DELIVERABLE", it throws an exception to halt the process, which prevents the use of an invalid email. The API returns a detailed JSON object that offers more than a simple valid or invalid status. The "quality_score" helps you rank borderline cases, while "autocorrect" can suggest fixes for common typos. Other boolean fields explain why an address fails, which allows for more nuanced rules, such as the rejection of disposable emails.

{
  "email": "johnsmith@gmail.com",
  "autocorrect": "",
  "deliverability": "DELIVERABLE",
  "quality_score": 0.9,
  "is_valid_format": { "value": true },
  "is_free_email": { "value": true },
  "is_disposable_email": { "value": false },
  "is_mx_found": { "value": true },
  "is_smtp_valid": { "value": true }
}

Final Thoughts

Traditional validation methods have significant weaknesses, as they fail to confirm deliverability or detect disposable addresses and require constant upkeep. Abstract API overcomes these issues with a single HTTPS call that provides a clear verdict. For reliable user email validation, consider the creation of a free account on Abstract API to get your API key.

Validate Emails with Abstract API
Stop invalid emails in your Java project. Implement email validation for cleaner, more reliable data.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required