public String getBestMxHost(String domain) throws NamingException { NamingEnumeration en = getAllMxRecords(domain); if ( en == null ) { return null; } int lowestPriority = Integer.MAX_VALUE; String prefHost = null; while ( en.hasMore() ) { String x = (String) en.next(); //System.out.println(x); String[] xs = x.split(" "); int priority = Integer.parseInt(xs[0]); String mxhost = xs[1].trim(); //System.out.println(mxhost + " @ " + priority); if ( priority < lowestPriority ) { prefHost = new String(mxhost); lowestPriority = priority; } } logger.debug("Preferred MX host for " + domain + " is " + prefHost + " with a priority of " + lowestPriority); return prefHost; } public NamingEnumeration getAllMxRecords(String domain) throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext( env ); Attributes attrs = ictx.getAttributes(domain, new String[] { "MX" }); Attribute attr = attrs.get( "MX" ); if ( attr == null ) { return null; } NamingEnumeration en = attr.getAll(); return en; }