Reputation: 328
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?
äöüëèéê@xkcd.com
// "valid" means worth attempting to send welcome message
static boolean isValidEmailAddress(String notNull);
Upvotes: -3
Views: 753
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:
jakarta.mail
as long as you're using Java 8 or newer. 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 @
.
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