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

Ensuring email addresses are valid is a key step for data integrity in many Java applications. You'll find five distinct implementation methods here, each with working code. We'll examine the shortcomings of traditional approaches and then see how Abstract API effectively addresses these common validation challenges.

How to Implement Email Validation in Java

Here are four common ways to validate email addresses in Java. Each method approaches the problem differently, from simple pattern matches to network-level checks for domain validity.

Regular Expressions with java.util.regex.Pattern

This method uses a regular expression (regex) to check email syntax. The java.util.regex.Pattern class compiles the expression once for repeated use, which is efficient. The matcher method then compares the input string against this compiled pattern to determine if it is a valid format.

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();

javax.mail.internet.InternetAddress Class

This approach leverages the parser built into the JavaMail API. The code attempts to create a new InternetAddress object from the candidate string and then calls its validate method. If the string does not conform to syntax rules, the method throws an AddressException, which signals an invalid email.

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

Apache Commons Validator

This method relies on the dedicated EmailValidator class from the Apache Commons Validator library. After you add the dependency, you can get a validator instance. The isValid method then returns a simple boolean result. The validator supports Internationalized Domain Names (IDN) and has configurable flags for local domains.

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

Syntax Check with DNS MX Lookup

This technique combines a syntax check with a network-level verification. After an initial pattern check confirms the email format is correct, the code performs a DNS lookup. It queries for a Mail Exchange (MX) record associated with the email's domain. The presence of an MX record indicates the domain is configured to accept 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 Email Validation in Java

Despite these available methods, robust email validation in Java presents significant hurdles. The official standards are far more complex than most libraries can handle, which leads to common implementation pitfalls.

  • Regular expressions and the InternetAddress class struggle with RFC grammar. They cannot handle complex cases like quoted strings, comments, or UTF-8 local parts. This results in validators that are either too complex or functionally incomplete for modern email addresses.
  • International emails with Unicode characters often cause failures. Legacy code that uses InternetAddress or third-party validators like Apache Commons Validator may not properly support the required punycode translation for domains or SMTPUTF8 for the local part.
  • Syntax checks with Pattern or InternetAddress ignore deliverability. An address can have a valid format but resolve to a domain with no mail server. This creates a risk of silent bounces that simple validation methods do not prevent.
  • Common regex patterns often reject valid edge cases like domains with hyphens or case-sensitive local parts. Loosened patterns may accept invalid formats. This creates a constant cycle of false negatives and false positives for the java.util.regex.Pattern method.

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 Java validation methods by the consolidation of multiple complex checks into a single HTTPS call.

  • The service chains a format check, typo autocorrect, MX and live SMTP tests, and heuristics for free, disposable, or role-based addresses to determine validity.
  • All logic, block-lists, and edge-case management stay on Abstract’s side, so your code requires no constant maintenance or updates.
  • It returns a simple JSON payload with a clear verdict, such as DELIVERABLE or UNDELIVERABLE, which your Java code can parse without complex logic.

How to Bring Abstract API to Your Dev Environment

Once you possess familiarity with Abstract’s capabilities, the addition of its email validation API to your project is simple.

  • Sign in at abstractapi.com, enable the “Email Verification & Validation” service, and copy your API key.
  • Confirm you have Java 11 or newer. For an older JDK, add OkHttp and a JSON library to your build.
  • Store the key as EMAIL_API_KEY inside 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 into a record and short-circuit your registration flow when the deliverability status is not “DELIVERABLE”.

Sample Email Validation Implementation with Abstract API

The Java 11+ code below demonstrates a practical implementation. It constructs a request URL with your API key and the user's email. The code then sends the request, receives the JSON response, and parses it to check the deliverability status. If the status is not "DELIVERABLE", it throws an exception to halt the process.

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"); }

The API returns a detailed JSON object. Here is a truncated sample:

{
  "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 }
}

Key fields in the response provide a complete picture of the email's validity:

  • deliverability: This field signals if the address can receive mail. You should typically block or flag anything other than DELIVERABLE.
  • quality_score: This score lets you rank borderline cases. A score below 0.3 often indicates a spam trap.
  • autocorrect: This field gives a safe suggestion for common typos, for example, gmial becomes gmail.
  • Boolean sub-objects: These explain why an address fails and support feature flags, such as the rejection of disposable addresses.

Final Thoughts

Traditional Java validation methods often fall short. They cannot guarantee an inbox exists or filter disposable addresses, and they demand constant maintenance. Abstract API replaces these fragile processes with a single, robust API call that returns a clear, actionable verdict on an email's true validity. To reliably validate user emails, consider the creation of an account on Abstract API to get your free 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