Recent Posts

    Authors

    Published

    Tag Cloud

    Java Code to validate email addresses

    Simple code to validate email addresses before they are sent

    com/aspc/remote/util/net/EmailUtil.java
    public final class EmailUtil
    {
        /**
         * http://www.regular-expressions.info/email.html
         */
        @RegEx
        private static final Pattern EMAIL_PATTERN = Pattern.compile(
                "^[A-Z0-9._%+\\-#']+@[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$", Pattern.CASE_INSENSITIVE);
    
        /**
         * Validate an email address.
         *
         * @param email the email to validate.
         * @param hostCache OPTIONAL cache of host names
         * @throws InvalidDataException details of the issue found.
         */
        public static void validate(final String email, final Map<String, String> hostCache) throws InvalidDataException
        {
            String invalidStrings[] =
            {
                "..", ".@"
            };
            for (String illegal : invalidStrings)
            {
                if (email.contains(illegal))
                {
                    throw new InvalidDataException("email " + email + " may not contain '" + illegal + "'");
                }
            }
    
            Matcher m = EMAIL_PATTERN.matcher(email.trim());
            if (m.matches() == false)
            {
                throw new InvalidDataException(email + " invalid email");
            }
    
            String[] split = email.split("@");
    
            if (split.length != 2)
            {
                throw new InvalidDataException("no @ symbol");
            }
            String tmpHost = split[1];
            String message = checkMX(tmpHost, null);
            if (message != null)
            {
                throw new InvalidDataException(message);
            }
        }
    
        /**
         * check the MX record
         *
         * @param hostName host to check
         * @param hostCache OPTIONAL cache of host names
         * @return message if NOT valid otherwise NULL
         */
        public static String checkMX(final String hostName, final Map<String, String> hostCache)
        {
            String message = null;
            if (hostCache != null)
            {
                message = hostCache.get(hostName);
            }
    
            if (message == null)
            {
                @SuppressWarnings("UseOfObsoleteCollectionType")
                Hashtable env = new Hashtable();
                env.put("java.naming.factory.initial",
                        "com.sun.jndi.dns.DnsContextFactory");
                try
                {
                    DirContext ictx = new InitialDirContext(env);
                    Attributes attrs =
                            ictx.getAttributes(hostName, new String[]
                    {
                        "MX"
                    });
                    Attribute attr = attrs.get("MX");
                    if (attr == null)
                    {
                        message = "no MX record for " + hostName;
                    }
                    else if (attr.size() > 0)
                    {
                        message = "";
                    }
                    else
                    {
                        message = "no MX record for " + hostName;
                    }
                } catch (NamingException e)
                {
                    message = e.getMessage();
                }
    
                if (hostCache != null)
                {
                    hostCache.put(hostName, message);
                }
            }
    
            if (message == null || message.isEmpty())
            {
                return null;
            }
    
            return message;
        }
    }