Article

How to Validate Email in Java Spring Boot: Syntax, DNS and Mailbox Checks

By Unlimited Verifier Team ·

Diagram of a Spring Boot email validation pipeline with syntax, DNS MX and SMTP mailbox check layers.

Summary

Email validation in Spring Boot works best in three layers: Bean Validation for syntax, a DNS MX lookup for domain checks, and an SMTP mailbox probe reserved for high-risk flows. The @Email annotation only tests format, so it will accept addresses that cannot receive mail. This guide shows the code for each layer and how to clean an existing user table.

To validate email in Spring Boot, use three layers: @NotBlank and @Email from Bean Validation for syntax, a JNDI DNS MX lookup to confirm the domain can receive mail, and an SMTP mailbox check reserved for high-risk flows. @Email on its own only tests format, so it will accept addresses that cannot receive mail. For the broader strategy, see our real-time email validation overview. This guide covers each layer with Spring Boot code, compares the Java options, and shows how to clean an existing user table.

Quick answer

What layers make up email validation in a Spring Boot app?

Email validation is a stack of checks, and each answers a different question. The cheapest check alone creates false confidence, while running every check on every request is slow and costly. Most teams run the syntax and domain checks on every write and save the mailbox-level checks for scheduled cleaning or high-value flows.

Layer Question it answers Java implementation Typical result Cost and latency
Syntax Is this a well-formed address? Bean Validation @Email, Commons EmailValidator, Jakarta Mail InternetAddress Pass or fail Local, negligible
Domain Does the domain exist and accept mail? JNDI DNS MX and A lookup Pass, fail or unknown Network call; cache by domain
Disposable and role Is this a throwaway or shared inbox? Domain list lookup, role-prefix list Flag Local; lists need upkeep
Mailbox Does this specific recipient exist? SMTP RCPT TO probe 250, 5xx, 4xx or timeout Seconds; depends on port 25
Catch-all and deliverability Does the server accept any address? Hosted verification API Valid, Risky or Invalid Remote call, batched

Bad addresses cost you more than bounces. Google's email sender guidelines say bulk senders should keep user-reported spam rates below 0.10% and avoid reaching 0.30%. Dead addresses and recycled spam traps are a common route to those complaints.

Bottom line: Validate syntax and domain on every write, and reserve mailbox checks for the flows that justify their cost.

Why is @Email not enough on its own?

@Email checks the shape of an address against a pattern. It doesn't ask whether any server will accept mail for it. Hibernate Validator, the provider Spring Boot uses by default, applies a permissive pattern. It can accept forms such as user@localhost that no public mail server will receive. It also treats null as valid, so @NotBlank must sit beside it.

Format checks also miss typos. jane@gmial.com is well formed and passes, even though the customer almost certainly meant gmail.com. Catching that requires typo-correction logic in the form itself, not in the validator.

A well-formed address can also belong to a mailbox that closed years ago. Only a domain, disposable or mailbox-level signal can reveal that.

Bottom line: @Email is a syntax filter. It is not proof that mail can be delivered.

How do you validate email syntax with Bean Validation?

Add spring-boot-starter-validation, annotate the DTO, and mark the controller parameter with @Valid. The starter pulls in Hibernate Validator as the provider.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
public record SignupRequest(
    @NotBlank
    @Size(max = 254)   // a common practical cap for an address
    @Email
    String email
) {}

@PostMapping("/signup")
ResponseEntity<Void> signup(@Valid @RequestBody SignupRequest req) {
    // ...
    return ResponseEntity.accepted().build();
}

@RestControllerAdvice
class ValidationAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail handle(MethodArgumentNotValidException ex) {
        ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        pd.setTitle("Invalid email");
        pd.setDetail("Please enter a valid email address.");
        return pd;
    }
}

Normalize input before validation runs. Trim whitespace and lowercase the domain. Leave the local part alone: RFC 5321 allows it to be case-sensitive, even though most large providers treat it case-insensitively. Preserve what the user typed, and document the normalization rule in code.

If you're on Spring Boot 2.x, the namespace is javax.validation. Mixing namespaces is a frequent reason validation silently doesn't run. ProblemDetail requires Spring Framework 6, which means Spring Boot 3.

Bottom line: Pair @NotBlank, @Size and @Email on every DTO, return a clean 400, and normalize before validating.

How do you check that a domain can receive mail in Java?

Query the domain's MX records through the JDK's built-in DNS provider. RFC 5321 says that when no MX record exists, the domain's A record acts as an implicit MX, so a domain with only an A record can still receive mail. Treat "no mail host" as invalid, and treat a DNS error as unknown.

public enum DomainStatus { HAS_MX, IMPLICIT_MX, NO_MAIL_HOST, UNKNOWN }

@Component
public class DnsMailHostResolver {

    public DomainStatus check(String domain) {
        Hashtable<String, String> env = new Hashtable<>();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        env.put("com.sun.jndi.dns.timeout.initial", "2000"); // milliseconds
        env.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext ctx = null;
        try {
            ctx = new InitialDirContext(env);
            if (ctx.getAttributes(domain, new String[]{"MX"}).get("MX") != null) {
                return DomainStatus.HAS_MX;
            }
            if (ctx.getAttributes(domain, new String[]{"A"}).get("A") != null) {
                return DomainStatus.IMPLICIT_MX;
            }
            return DomainStatus.NO_MAIL_HOST;
        } catch (NameNotFoundException e) {
            return DomainStatus.NO_MAIL_HOST;   // domain does not exist
        } catch (NamingException e) {
            return DomainStatus.UNKNOWN;        // timeout or resolver failure
        } finally {
            if (ctx != null) {
                try { ctx.close(); } catch (NamingException ignored) { }
            }
        }
    }
}

Three design decisions matter here:

Does the lookup slow down signup? A cached result returns from memory. An uncached one costs at least one round trip to your resolver. The 2-second timeout caps the worst case, so a slow DNS server can't hold a request thread for long.

Bottom line: Check MX, fall back to A per RFC 5321, cache by domain, and never reject a user because your own DNS timed out.

Should your Spring Boot app run an SMTP mailbox check?

An SMTP mailbox check connects to the recipient's MX host, sends EHLO, MAIL FROM and RCPT TO, reads the reply, and quits without sending a message. RFC 5321 defines the reply codes: a 250 accepts the recipient, a 5xx rejects it permanently, and a 4xx signals a temporary condition.

Server response Meaning Recommended handling
250 Recipient accepted Mark deliverable, but it may be a catch-all
550 and other 5xx Permanent rejection, such as no such mailbox Mark Invalid
4xx Temporary failure, such as greylisting or a busy server Mark unknown and retry later
Timeout or refused connection No usable answer Mark unknown

Four limits explain why most teams don't use SMTP probes as a signup gate:

Run SMTP checks in batch, asynchronously and rate-limited, and store the results. The SMTP email check guide covers the protocol flow in detail.

Bottom line: Treat SMTP as a background signal with four outcomes, not a yes-or-no signup gate.

Which Java email validation option should you choose?

No single option covers every layer. Use the table to match each one to the job it actually does.

Option What it checks Specific strengths Specific limitations
Bean Validation @Email (Hibernate Validator) Permissive format pattern Ships with spring-boot-starter-validation; annotate DTOs with no extra code No DNS; accepts some non-deliverable forms; null passes
Apache Commons EmailValidator Format plus TLD checks getInstance(allowLocal, allowTld) controls local-only and single-label domains Its TLD data needs updating as new TLDs are delegated
Jakarta Mail InternetAddress Strict RFC-style parsing new InternetAddress(s, true) throws AddressException on malformed input Syntax only; no domain or mailbox signal
Custom JNDI MX/A resolver Domain can receive mail No vendor cost; you set timeouts and caching You own caching, retries and failure handling; no mailbox signal
Custom SMTP probe Mailbox-level response Direct response from the receiving server Port 25 blocking; catch-all ambiguity; reputational risk
Hosted verification API (Unlimited Verifier) Syntax, domain/MX, SMTP mailbox, catch-all, disposable and role flags Sorts results into Valid, Risky and Invalid; batches of up to 10,000 emails per request API access requires the Pro plan; you call REST rather than a Java library

Unlimited Verifier's email verification API handles single-email checks and batches of up to 10,000 emails per request. For the wider pattern, see email verification API and automation. The Free plan has no API access, so prototype with the free email checker before you build against the API.

For the wider market, our comparison of verification tools covers the options beyond Java. Unlimited Verifier also publishes its verification engine as open source on GitHub, so you can read the logic before you rely on it. If your services are in Go, see our Go email validation packages guide.

Bottom line: Use Bean Validation for format, a custom resolver for domains, and a hosted API when you need mailbox-level and catch-all signals at scale.

How do you build a reusable @DeliverableEmail constraint?

Wrap the domain check in a custom constraint so any DTO can reuse it. Spring's validator factory supports dependency injection, so the validator can receive your resolver.

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DeliverableEmailValidator.class)
public @interface DeliverableEmail {
    String message() default "Email domain cannot receive mail";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

@Component
class DeliverableEmailValidator implements ConstraintValidator<DeliverableEmail, String> {
    private final DnsMailHostResolver resolver;

    DeliverableEmailValidator(DnsMailHostResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public boolean isValid(String email, ConstraintValidatorContext ctx) {
        if (email == null || !email.contains("@")) return true; // syntax layer handles this
        String domain = email.substring(email.lastIndexOf('@') + 1);
        return resolver.check(domain) != DomainStatus.NO_MAIL_HOST;
    }
}

Because UNKNOWN returns true, a DNS hiccup never blocks a real customer. Pair the constraint with a scheduled job that re-checks unknown addresses and promotes or demotes them.

Bottom line: Put the domain check behind a constraint, leave syntax to @Email, and fail open on unknown results.

How do you call a hosted verifier from Spring Boot?

Create a RestClient bean, keep the API key in configuration, and send batches of at most 10,000 emails per request. RestClient requires Spring Boot 3.2 or later. Copy the endpoint paths and authentication header from the API documentation on your key page rather than guessing them.

@Configuration
class VerifierConfig {
    @Bean
    RestClient verifierClient(@Value("${verifier.base-url}") String baseUrl,
                              @Value("${verifier.api-key}") String apiKey) {
        return RestClient.builder()
            .baseUrl(baseUrl)
            // Replace with the auth scheme shown in the API docs
            .defaultHeader(HttpHeaders.AUTHORIZATION, apiKey)
            .build();
    }
}

// Requires java.util.stream.IntStream and java.util.List
static <T> List<List<T>> chunks(List<T> items, int size) {
    return IntStream.range(0, (items.size() + size - 1) / size)
        .mapToObj(i -> items.subList(i * size, Math.min(items.size(), (i + 1) * size)))
        .toList();
}

Send each chunk to the batch endpoint, and back off when you receive HTTP 429. Our guide to API rate limits explains retry patterns.

Budget the API allowance before you schedule jobs. Pro includes 100,000 API emails a month. A nightly re-check of 3,000 addresses uses 90,000 of them over 30 days, which leaves 10,000 for other calls, assuming single-email checks draw on the same allowance. Standard verification is unlimited on every plan, so the budget that matters is the API emails and deep verifications.

Bottom line: Keep the key in config, batch at 10,000, handle 429 with backoff, and budget your monthly API emails before scheduling re-checks.

How do you clean an existing user table?

For teams running email verification for ecommerce and SaaS workflows, the backlog is usually the bigger problem than new signups. Here is a worked example.

Scenario (hypothetical): A SaaS company has 180,000 user emails collected across three signup forms over six years. It wants to clean them and then add validation to the signup endpoint. It is on Pro at $29 a month.

Step 1: Split the work across the two routes.

A 25,000-row CSV with an email column and a user ID is roughly 1.5 MB at about 60 bytes per row (an estimate). That is well under the 10 MB upload limit, so the row cap is the constraint that matters.

Step 2: Deep-check the risky subset. Pro includes 25,000 deep verifications a month. If 18,000 addresses come back Risky, a deep re-check of that group fits within the allowance.

Step 3: Read the buckets (hypothetical results):

Bucket Count Share of 180,000
Valid 150,000 83.3%
Risky 18,000 10.0%
Invalid 12,000 6.7%

Step 4: Cost. One Pro month is $29. Billed annually, Pro is $25 a month, or $300 a year. Using all 100,000 API emails in a month works out to $29 ÷ 100 = $0.29 per 1,000 emails. That is a derived figure from the plan price, not a published per-email rate, and it is the kind of number to check against your own usage before you budget. The upload route adds no per-email fee. For more on how pricing models compare, see email verification pricing.

Step 5: Write results back. Pro keeps results for 30 days, so export and store them the same day. Add email_status (valid, risky, invalid, unchecked) and checked_at columns to the user table. Signup code, marketing segments and the next re-check then all read from one source of truth. The list maintenance guide covers the cadence.

For a pilot, the Free plan allows 25 lists a month of up to 150 emails each, which is 25 × 150 = 3,750 emails a month, with no API access.

Bottom line: A 180,000-row cleanup fits in one month on Pro: 10 API batches, 4 uploads and $29 of spend, as long as you save results before the 30-day window closes.

How do you add email validation to a signup endpoint?

  1. Confirm the starter. Check that spring-boot-starter-validation is in your build file and that you're on Spring Boot 3 with the jakarta.validation namespace.
  2. Annotate the DTO. Add @NotBlank, @Size(max = 254), @Email and @DeliverableEmail to the email field.
  3. Mark the endpoint. Add @Valid to the @RequestBody parameter, and add a @RestControllerAdvice that returns a ProblemDetail with status 400.
  4. Add the resolver. Create DnsMailHostResolver with a 2-second timeout, one retry, and a cache keyed by domain.
  5. Normalize. Trim whitespace and lowercase the domain before validation runs.
  6. Test the edge cases. Write a JUnit test using Validation.buildDefaultValidatorFactory().getValidator(). Cover a valid address, a typo domain, a single-label address like user@localhost, a null value, and a domain with no mail host.
  7. Export existing users. Write the email column to CSV, and keep the user ID beside it so results can be joined back.
  8. Verify the file. Upload and verify a list. The email column is detected automatically, and results export as CSV, Excel or JSON.
  9. Write results back. Update email_status and checked_at on each row, and suppress Invalid addresses from future sends.
  10. Schedule re-checks. Run a monthly job that batches unchecked and stale addresses through the API.

For the frontend half of the job, see client-side vs server-side email validation, and for form-level UX, how to add real-time email verification to signup forms. Before you build on a TypeScript client, remember that the server check is the one that matters.

Bottom line: Validate at the form, check the domain, clean the backlog in batches, and re-check on a schedule.

What should your app do with Risky results?

The right action depends on the flow, not just the bucket. Use this table as a starting policy.

Result At signup In batch cleaning Rationale
Valid Accept Keep and mark valid No reason to act
Invalid (no mail host or permanent 5xx) Reject with a generic message Suppress from sends Mail cannot be delivered
Risky: catch-all Accept for B2B account contacts Send last, in a small ramp The server accepts every address, so the mailbox is unconfirmed
Risky: disposable Block for free trials Flag and suppress Throwaway inboxes rarely engage
Risky: role address (info@, sales@) Accept for B2B Exclude from personalised sequences A shared inbox doesn't map to one person's consent
Unknown (DNS timeout, 4xx) Accept and queue a re-check Retry later Your infrastructure failed, not the address

For catch-all domains, the catch-all email verification page explains how Unlimited Verifier flags them. For B2B prospect lists, catch-all handling is covered in email verification for sales prospecting. Blocking every catch-all domain is a common overcorrection that discards legitimate business contacts.

Consent and list hygiene matter as much as deliverability. Verification confirms an address can receive mail. It does not prove the person opted in, so keep your consent records alongside the results. This is the core of email verification compliance and hygiene.

Bottom line: Let the flow decide. Block disposables at signup, hold catch-alls back from your first sends, and retry unknowns rather than rejecting them.

What mistakes break email validation in Java?

Bottom line: Most failures come from treating one check as the whole answer, or from letting infrastructure problems look like bad data.

How we compared (and limitations)

This guide is based on public documentation: the Bean Validation specification, Hibernate Validator documentation, Apache Commons Validator, Jakarta Mail, RFC 5321 for SMTP reply codes and implicit MX, and the Spring Boot reference documentation. We have not benchmarked these libraries against each other, and we have not run the code samples against every Spring Boot version. Check them against your version before you ship.

DNS and SMTP behaviour depends on your resolver and network. Port 25 access varies by hosting provider, and mailbox responses vary by provider and can change without notice.

Unlimited Verifier's 99.5% accuracy figure for deep verification is the company's own stated number, not an independent benchmark. The worked example's counts and percentages are hypothetical, though the plan limits and arithmetic are real. The $0.29 per 1,000 figure is derived from the Pro price, not a published rate.

Three-layer validation flow for a signup endpoint

  1. Bean Validation on the DTO: annotate the field with @NotBlank, @Size(max = 254) and @Email. Reject the request if any fails.
  2. Domain lookup: take the part after the @ and query DNS for MX records using the JDK's JNDI DNS provider with short timeouts. If there is no MX record, check for an A record.
  3. Interpret the result: a definitive negative (no MX and no A, or NXDOMAIN) returns invalid. A timeout or server error returns unknown, so the signup proceeds with a pending status.
  4. Cache by domain: store the domain result for a set period so repeated signups from the same provider skip the lookup.
  5. Persist the outcome: save the status and check date on the user record.
  6. Queue mailbox checks separately: send only high-risk or scheduled cases to an asynchronous, rate-limited SMTP probe or a hosted verification service.

Frequently asked questions

Does @Email in Spring Boot check whether an email address really exists?

No. @Email only checks that the address matches a syntax pattern. It does not confirm that the domain has mail servers or that the mailbox exists. To check the domain, add a DNS MX lookup. To check the specific mailbox, you need an SMTP probe or a hosted verification service, and both have trade-offs in cost, latency and reliability.

Does @Email accept addresses like user@localhost?

Yes, Hibernate Validator's default pattern can accept forms like user@localhost that no public mail server will receive. Add a domain check that requires a real DNS MX or A record to reject these. Also pair @Email with @NotBlank, because @Email treats null as valid.

How do I check MX records in Java without a third-party library?

Use the JDK's built-in JNDI DNS provider. Create an InitialDirContext with the com.sun.jndi.dns.DnsContextFactory factory, then query the domain for the MX record type. Set short connect and read timeouts. If there is no MX record, RFC 5321 allows falling back to the A record. Cache results by domain so you do not repeat lookups for common providers.

Should I run an SMTP mailbox check on every signup?

Usually not. SMTP probes add seconds of latency, are often blocked on outbound port 25, and some providers give ambiguous answers. Most teams run syntax and domain checks on every write and reserve mailbox checks for scheduled cleaning, high-value actions or flows where a bounce is costly. Run probes asynchronously and rate-limit them.

What should my app do when a DNS lookup times out?

Treat the result as unknown rather than invalid. A timeout usually reflects network or resolver trouble, not a bad address. Accept the write with a pending or unverified status, retry later, and only block the address when DNS returns a definitive negative answer such as NXDOMAIN.

What is a catch-all domain and why does it matter?

A catch-all domain accepts mail for any local part, so an SMTP check returns success even when the mailbox does not exist. This makes mailbox-level results for those domains risky. Label them as risky rather than valid, and rely on engagement data or a hosted verification service to judge deliverability.

How do I detect disposable or role-based email addresses?

Compare the domain against a maintained list of disposable providers, and check the local part against common role prefixes such as info, admin, support and sales. These checks are local and fast, but the lists need regular updates. Flag matches for review rather than rejecting them outright, since some role inboxes are legitimate.

How do I clean an existing user table of invalid email addresses?

Run a batch job that first applies the syntax check, then the domain check with per-domain caching, and finally mailbox checks for a sample or for flagged rows. Store the status and the check date in your own database so you do not re-verify unnecessarily. Process in pages, log failures, and never delete accounts without reviewing the results.

Should I store email validation results in my own database?

Yes. Keep the status, the check type and the check date in your own tables. Relying only on a vendor's stored results makes your app dependent on their retention policies. Your own records also let you decide when a result is stale enough to re-check.

Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification

Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.

Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.

Free Pro
Price $0 $29/month ($25/month billed annually)
Lists 25 a month, up to 150 emails each Unlimited, up to 25,000 emails each
Deep verifications 750 a month 25,000 a month
API access No Yes (100,000 emails a month)
Result retention 24 hours 30 days

Why teams choose Unlimited Verifier

Unlimited Verifier states 99.5% accuracy for deep verification.

Create a free account and verify your next list before you hit send.

Want to test a single address first? Try the free email checker.