To Check if the domain of an email address is valid or not, pass the email address to the below method as an argument and execute it, it will return true or false by checking if the email id you entered has valid domain or not :
private static boolean doLookup( String hostName ) { try { String[] emailDN=hostName.split("@"); // System.out.println(emailDN[0]+" "+emailDN[1]); Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext( env ); Attributes attrs = ictx.getAttributes( emailDN[1], new String[] { "MX" }); Attribute attr = attrs.get( "MX" ); if( attr == null ) return(true); //return( attr.size() ); return true; } catch (NamingException e) { // TODO Auto-generated catch block //e.printStackTrace(); return false; } } public static void main(String[] args){ if(!doLookup("Input email address")){ System.out.printLn(“Invalid domain”); } else { System.out.printLn(“Valid”); } }
Input : myname@abc.com
Output : Invalid domain
Input : myname@webners.com
Output : Valid
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.
This code is not checking valid domain. It always return invalid domain even the domain is corrent. I tried gmail ids.