W3docs

What is the best Java email address validation method?

There are a few different approaches you can take to validate email addresses in Java. Here are some options:

There are a few different approaches you can take to validate email addresses in Java. Here are some options:

  1. Regular expressions: You can use a regular expression to check that the email address has the correct format. While this is a relatively simple approach, it can be difficult to create a regular expression that is both comprehensive and performant.
    public boolean isValidEmail(String email) {
        String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        return email != null && email.matches(regex);
    }
  2. Apache Commons Validator: The Apache Commons Validator library includes a EmailValidator class that can be used to validate email addresses. This approach is simple and easy to use, but may not be as thorough as some other options. Add the following dependency to your project:
    `<dependency>`
        `<groupId>`commons-validator`</groupId>`
        `<artifactId>`commons-validator`</artifactId>`
        `<version>`1.9.0`</version>`
    `</dependency>`
    Usage example:
    import org.apache.commons.validator.routines.EmailValidator;
    
    EmailValidator validator = EmailValidator.getInstance();
    boolean isValid = validator.isValid("[email protected]");
  3. JavaMail API: The JavaMail API includes a javax.mail.internet.InternetAddress class that can be used to validate email addresses. This approach is more comprehensive and checks syntax per RFC 5322, though it does not verify domain existence via DNS. However, it requires more setup and may be more resource-intensive than some other options.
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.AddressException;
    
    try {
        InternetAddress emailAddr = new InternetAddress("[email protected]");
        emailAddr.validate();
        // Email syntax is valid
    } catch (AddressException ex) {
        // Email syntax is invalid
    }
MethodComplexityThoroughnessDependencies
Regular ExpressionsLowSyntax onlyNone
Apache Commons ValidatorLowRFC 5322 syntaxcommons-validator
JavaMail APIMediumRFC 5322 syntaxjavax.mail / jakarta.mail

Ultimately, the best method for email address validation will depend on your specific requirements and constraints. You may want to consider factors such as performance, ease of use, and thoroughness when choosing a validation method.

I hope this helps! Let me know if you have any questions.