Validate email addresses

When a user inputs an email address, it may be validated by passing it to the constructor of InternetAddress. If it doesn't comply with RFC822, then a checked exception will be thrown.

Note that a simple local address, such as "joe", complies with RFC822. If this type of address is undesired (and it usually is), then some extra validation will be needed.

Basing email validation on InternetAddress is highly recommended. A common mistake is to implement an email address parser on your own, using a regular expression or something similar. This is almost always a bad idea: the details are too hard to get right, and you'll likely make mistakes. Furthermore, you won't be aware of the mistakes until your code is in production.

Example

Here's a class that validates email addresses through the static method isValidEmailAddress. Note that it treats local addresses as invalid (as implemented by the call to hasNameAndDomain).

package hirondelle.web4j.util;

import java.util.regex.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Static convenience methods for common web-related tasks.
*/
public final class WebUtil {
  
  /**
  * Validate the form of an email address.
  *
  * <P>Return <tt>true</tt> only if 
  *<ul> 
  * <li> <tt>aEmailAddress</tt> can successfully construct an 
  * {@link javax.mail.internet.InternetAddress} 
  * <li> when parsed with "@" as delimiter, <tt>aEmailAddress</tt> contains 
  * two tokens which satisfy {@link hirondelle.web4j.util.Util#textHasContent}.
  *</ul>
  *
  *<P> The second condition arises since local email addresses, simply of the form
  * "<tt>albert</tt>", for example, are valid for 
  * {@link javax.mail.internet.InternetAddress}, but almost always undesired.
  */
  public static boolean isValidEmailAddress(String aEmailAddress){
    if (aEmailAddress == null) return false;
    boolean result = true;
    try {
      InternetAddress emailAddr = new InternetAddress(aEmailAddress);
      if (! hasNameAndDomain(aEmailAddress)) {
        result = false;
      }
    }
    catch (AddressException ex){
      result = false;
    }
    return result;
  }

  private static boolean hasNameAndDomain(String aEmailAddress){
    String[] tokens = aEmailAddress.split("@");
    return 
      tokens.length == 2 &&
      Util.textHasContent(tokens[0]) && 
      Util.textHasContent(tokens[1]) 
    ;
  }
  
  //..elided
}
 

See Also :
Send trouble ticket emails
A Web App Framework WEB4J
Launch other applications