Recent Posts

    Authors

    Published

    Tag Cloud

    301 302 404 accessibility accounts ACLs advertising aggregation Agile Analytics android APP Article attachments awards backup BCM beta browser business continuity Calendar case-study categories Chrome citigroup cms codes coding standards Complaints contact management software control panel crm CSS customer management software customer relationship system customize database DataModel DDoS demo design designer device compatibility difference distribute a published article via email DND DNS documents drag & drop Editor email EOL erp event Excel featured feeds file manager file sharing file volume Firefox Firewall HA hack Handlebar how-to HTML HTML5 HTTP HTTPS iCal IE Instructions intranet iOS iPad Java JavaScript JDBC JDK Jenkins Job Track Journal JSON JVM landing-page launcher layered database layout logging login mac marketing menu meta Microsoft Outlook mobile module modules mustache navigation NTLM offline page painter password passwords PCI policy poll pricing privacy PROXY publish publisher publsher PWA redirect Redundancy release release-notes Report Tool Reports Responsive ReST RESTFul Rich text RSS Safari sandbox sanity schedule scrum search security SEO sessions setup shipping site builder source spell SQL Injection SSL SSO standards store stSoftware support survey Swagger Task template testimonial Threads timezone tinyMCE Transaction Search trigger twitter twitter bootstrap Ubuntu unit tests unsubscribe URL validation WC3 AAA web folders web services webdav windows 8 wizard workflow WYSIWYG XLS XLST XML XPath XSS

    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;
        }
    }