Proper email validation in Spring Boot is a foundational step for data integrity and reliable user sign-ups. We will cover five implementation methods using code examples, discuss the limitations of these traditional techniques, and then show how Abstract API addresses their shortcomings.
How to Implement Email Validation in Spring Boot
Here are four common methods to implement email validation in a Spring Boot application, from built-in annotations to custom runtime checks, each with its own implementation details.
Hibernate-Validator's @Email Annotation
The simplest method uses the out-of-the-box "@Email" annotation. You first add the "spring-boot-starter-validation" dependency, which includes Hibernate-Validator. Then, you annotate the relevant field in your Data Transfer Object (DTO).
Spring automatically injects a "MethodValidationPostProcessor" that triggers the validation when the object is bound. The default implementation uses a permissive regular expression that validates syntax but may accept domains without a top-level domain, as noted on Stack Overflow.
public record SignupCmd(
@Email(message = "Address syntax is wrong")
String email
) {}
A Hardened Annotation with an Extra Pattern
You can create a more strict validation by enhancement of the default "@Email" annotation. For Hibernate-Validator 6.x or newer, you can override the regular expression directly within the annotation to enforce a top-level domain.
A second option is to compose a new constraint. This involves the creation of a custom annotation that combines both "@Email" and "@Pattern". This approach keeps the built-in local-part parsing but adds a guard for a dot in the domain name.
// Option A: Override in place
@Email(regexp = ".+@.+\\..+", message = "Missing top-level domain")
String email;
// Option B: Compose a custom constraint
@Email
@Pattern(regexp = ".+@.+\\..+")
@ReportAsSingleViolation
public @interface StrictEmail {}
A Custom ConstraintValidator with Apache Commons-Validator
For more control, you can build a custom validator that delegates to a third-party library like Apache Commons Validator. First, add the "commons-validator" dependency to your project. Then, create a custom annotation that points to your validator class.
The validator class implements the "ConstraintValidator" interface. Its "isValid" method uses the "EmailValidator" from the Apache Commons library to perform the check. This is a widely discussed validation pattern in Java.
// 1. The custom annotation
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = CommonsEmailValidator.class)
public @interface ValidEmail {
String message() default "Bad email";
// Required boilerplate
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
// 2. The validator implementation
public class CommonsEmailValidator implements ConstraintValidator<ValidEmail, String> {
private static final EmailValidator DELEGATE = EmailValidator.getInstance(false);
public boolean isValid(String value, ConstraintValidatorContext ctx) {
return value == null || DELEGATE.isValid(value);
}
}
Runtime Validation with an Active MX-Lookup
This method performs a live check to see if a domain is configured to receive email. The process begins with a basic syntax parse. After that, it queries the Domain Name System (DNS) for the domain's Mail Exchange (MX) records.
A valid domain will have at least one MX record. Because this check involves network I/O, it is best to wrap the logic in a "CompletableFuture" or use Project Reactor. This practice prevents the block of request threads and allows for non-blocking execution.
// First, parse syntax
new InternetAddress(addr).validate();
// Then, verify domain's MX records
DirContext ctx = new InitialDirContext(env);
Attributes mx = ctx.getAttributes("dns:/" + domain, new String[]{"MX"});
boolean valid = mx.size() > 0;
Challenges of Email Validation in Spring Boot
Traditional validation methods in Spring Boot present several technical hurdles. These approaches often create brittle code, fail to support global users, and cannot confirm if an inbox actually exists.
- The default @Email annotation accepts invalid syntax, like addresses without a top-level domain. Developers add extra @Pattern rules to compensate, which makes the validation logic fragile and difficult to maintain.
- Standard validators like @Email and Apache Commons-Validator are ASCII-centric. They reject internationalized addresses with non-Latin characters, which limits a service's ability to support a global user base without extra libraries.
- Complex regular expressions, used in hardened annotations, struggle with unusual but legal RFC formats. These patterns become unreadable, perform unpredictably, and introduce security risks like Regular Expression Denial of Service (ReDoS).
- Even an active MX-lookup only confirms a domain can receive mail, not that a specific mailbox exists. An address can pass this check yet belong to a disposable domain or a spam-filtered inbox.
Validate Emails with Abstract API
Stop invalid sign-ups and improve data accuracy in your Spring Boot application with email validation.
Get started for free
How Abstract API Handles Email Validation in Spring Boot
Abstract API addresses the core weaknesses of traditional email validation methods. It performs a deeper analysis that goes beyond simple pattern matches or DNS lookups.
- It executes a comprehensive series of checks that surpass basic regex. The validation includes syntax, autocorrect, MX records, SMTP, and tests for free, disposable, or role-based domains.
- It returns a clear, real-time deliverability status. This single field allows for immediate decisions on user signups without the delay of a potential email bounce.
- It offloads the maintenance of complex validation rules. The Abstract team constantly updates disposable domain lists and MX heuristics, so your codebase does not require frequent changes.
- It provides operational reliability through a high uptime SLA and a managed cloud endpoint. This eliminates the need to operate your own network-level probes or manage infrastructure for email checks.
How to Bring Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you can add its email validation API to your project with ease. The setup requires a few straightforward steps to integrate the endpoint into your Spring Boot application.
- Add a dependency: Include WebClient for reactive HTTP calls. Add
org.springframework.boot:spring-boot-starter-webflux
to your build file. - Configure your API key: Place your key in the
application.yml
file for secure access. - Create a client: Define a WebClient bean that points to the Abstract API endpoint.
- Build a validation component: Write a class that uses the WebClient to call the API with a user's email.
- Map the response: Create a Data Transfer Object, like a Java record, to hold the JSON response from the API.
- Integrate the check: Use the validation component within your application's logic, for example, in a custom
ConstraintValidator
.
@Bean
WebClient abstractEmailClient(WebClient.Builder b) {
return b.baseUrl("https://emailvalidation.abstractapi.com/v1").build();
}
@Service
public class EmailValidationService {
private final WebClient client;
@Value("${abstract.email.api-key}") String apiKey;
public EmailValidationService(WebClient c){ this.client = c; }
public Mono<AbstractEmailResponse> validate(String email){
return client.get()
.uri(u -> u.queryParam("api_key", apiKey)
.queryParam("email", email).build())
.retrieve().bodyToMono(AbstractEmailResponse.class);
}
}
Sample Email Validation Implementation with Abstract API
After you implement the setup, a call to the API with an email like "johnsmith@gmail.com" returns a detailed JSON object. This response provides a clear picture of the email's validity beyond a simple format check. Below is a sample response and an explanation of what it communicates.
{
"email":"johnsmith@gmail.com",
"autocorrect":"",
"deliverability":"DELIVERABLE",
"quality_score":0.9,
"is_valid_format":{"value":true,"text":"TRUE"},
"is_free_email":{"value":true,"text":"TRUE"},
"is_disposable_email":{"value":false,"text":"FALSE"},
"is_role_email":{"value":false,"text":"FALSE"},
"is_catchall_email":{"value":false,"text":"FALSE"},
"is_mx_found":{"value":true,"text":"TRUE"},
"is_smtp_valid":{"value":true,"text":"TRUE"}
}
- The format is correct, and the API suggests no autocorrection.
- Abstract reached the mail exchange server and confirmed the SMTP status, so the mailbox almost certainly exists.
- The domain is a free provider but not a disposable one. It represents a personal address, not a role-based one like "support@".
- A high "quality_score" and a "DELIVERABLE" status mean you can safely accept the user signup or send an email immediately.
Final Thoughts
Traditional email validation often depends on regular expressions that cannot detect disposable domains or SMTP issues. This approach creates gaps in data quality. Abstract API closes these gaps with a multi-layered check that confirms deliverability in real time.
A free API key from Abstract API allows you to implement these reliable checks in your own project.
Validate Emails with Abstract API
Improve your application's data quality by adding reliable email validation to your Spring Boot project.
Get started for free