Simple question with a complex answer; searching Stack Overflow yields much debate and practical knowledge.
However, I have a pithy retort for them: Have you considered sending a message to see who writes back? Else:
- First, impose any length limits and any explicit allow/block list(s) you prefer.
- Next, consider
jakarta.mail
as long as you're using Java 8 or newer.
- Avoid regex entirely, BUT if you MUST, this will do:
private static final String NLP = Pattern.compile("[\\p{Alnum}\\p{Punct}&&[^@]]+").pattern();
private static final Pattern VALID_ENOUGH_EMAIL_ADDRESS =
Pattern.compile(String.join("@", NLP, NLP), Pattern.UNICODE_CHARACTER_CLASS);
In plain English: "any number or letter, or punctuation except literal @
, at least once" on either side of one literal @
.
Foot notes:
This library claims to implement RFC822, which has been superseded. Twice. And, it probably will be again and again.
https://eclipse-ee4j.github.io/mail/
public static void boolean isValidEmailAddress(String notNull) {
// impose whatever extra pre-flight check you like on ^^^
try {
new InternetAddress(notNull, true); // v2.0.0 works w/ Unicode
return true;
} catch (AddressException e) {
// log or recover however you want
return false;
}
}
Note, this will probably accept messages that ARE NOT single valid email addresses recognized by most systems; if your system has unique requirements, refer to those. And if it doesn't, you can probably use the Java/Spring validation annotation for @Email
with the proper pattern rather than writing your own implementation that has to do with emoji and umlauts and who knows what else in 2020 and beyond.
https://en.wikipedia.org/wiki/International_email