hagemt
hagemt

Reputation: 328

Java 8/11+ validate email address syntax w/o Pattern?

Edit: Apparently, what I've done here is taboo. 🤷 C'est la vie.

I know there are at least as many answers to this on SO as there are RFCs for email, and I have my own answer to this question, which I want to put out into the world for feedback. How should my application ensure an arbitrary String contains exactly ONE valid email address?

// "valid" means worth attempting to send welcome message
static boolean isValidEmailAddress(String notNull);

Upvotes: -3

Views: 753

Answers (1)

hagemt
hagemt

Reputation: 328

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:

  1. First, impose any length limits and any explicit allow/block list(s) you prefer.
  2. Next, consider jakarta.mail as long as you're using Java 8 or newer.
  3. 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

Upvotes: -3

Related Questions