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".

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.

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.

Frequently Asked Questions

What are the main ways to validate email addresses in Java?

Java developers have five common options: regex with java.util.regex.Pattern, the InternetAddress class from the JavaMail API, Apache Commons Validator's EmailValidator, a DNS MX record lookup, and calling a third-party API like Abstract. Each method trades off simplicity against how thoroughly it verifies deliverability.

Why isn't regex alone enough for email validation in Java?

Regex cannot fully express the RFC email grammar, so overly strict patterns reject valid addresses that contain hyphens, unusual formatting, or Unicode characters in international email addresses. Even a pattern that passes every format check gives no indication of whether the domain can actually receive mail.

How does Abstract's Email Validation API improve on local validation methods?

Abstract chains format validation, typo correction, MX record lookup, and live SMTP testing into a single HTTPS call, and also detects disposable, role-based, and catch-all addresses through internal heuristics. The JSON response includes a deliverability field and a quality_score, giving you far more signal than a simple valid/invalid result.

How do I call the Abstract Email Validation API from Java?

Sign up at Abstract, enable Email Verification & Validation, and store your API key as an environment variable. Then send an HTTPS GET request to https://emailvalidation.abstractapi.com/v1/ with your key and the target address as query parameters, and parse the JSON response, checking deliverability for the overall verdict.

What does the Abstract email validation response look like?

The response is a JSON object with fields like deliverability (e.g., "DELIVERABLE"), quality_score, is_valid_format, is_free_email, is_disposable_email, is_mx_found, and is_smtp_valid. This lets you make nuanced decisions (for example, accepting an address but flagging it as disposable), rather than a binary pass/fail.

What is the advantage of a DNS MX lookup over regex for email validation in Java?

An MX lookup queries DNS to confirm that the email's domain actually has mail server records configured, catching addresses that pass format checks but belong to non-existent or misconfigured domains. However, it still cannot verify that the specific mailbox exists. For that level of confidence, an SMTP-level check (as Abstract performs) is required.

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