I was researching best possible way to check if a String
was a valid email Address. I am now fixated on two options, viz., using javax.mail.internet.InternetAddress
; or using Apache Commons EmailValidator
, which internally uses complicated regex parser.
I was wondering if there is any advantages on picking one over the other in terms of correctness, or is both just fine? I know for a fact that InternetAddress
doesn't handle non-ascii characters efficiently in some cases.
The closed question What is the best Java email address validation method? received several answers, and while a few pretend to offer the best way, several propose the Apache Commons Validator. You can use an EmailValidator from this library as follows:
import org.apache.commons.validator.routines.EmailValidator;
...
EmailValidator validator = EmailValidator.getInstance();
if (validator.isValid(email)) {
// is valid, do something
} else {
// is invalid, do something
}
The isValid
method checks if a string is a valid email address.
As of 2024, starting from Commons Validator version 1.6, or even before, and including the latest version 1.8.0, the validation is not sufficiently strict, at least if you expect compliance with RFC 5321. So-called "internationalized email addresses", only valid per the proposed standard RFC 6530, for example, françois@lévêque.net
, are also reported as valid. As the EmailValidator JavaDoc indicates:
This implementation is not guaranteed to catch all possible errors in an email address.