Checking Email and DNS MX records in ColdFusion with Java DnsContextFactory and Google Public DNS
Nice short function using Google's DNS and Java DnsContextFactory. Based on a script I saw here
Note; a trailing space fails here; so make sure that doesn't waste some time of your day when validating.
<cffunction name="validateEmailAndMXRecord" returntype="Struct">
<cfargument name="emailAddress" required="true">
<cfargument name="checkMXRecord" required="false" default="true">
<cfscript>
var env = CreateObject("java", "java.util.Hashtable");
var dirContext = CreateObject("java", "javax.naming.directory.InitialDirContext");
var type = ArrayNew(1);
var attributes = "";
var atribEnum = "";
var stReturn = StructNew();
</cfscript>
<cfif isvalid("email", arguments.emailAddress)><!--- basic validation (possibly not good to rely on this.) --->
<cfscript>
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns://8.8.8.8"); // Using Googles Public DNS
env.put("com.sun.jndi.dns.timeout.initial", "2000");
env.put("com.sun.jndi.dns.timeout.retries", "3");
dirContext.init(env);
type[1] = "MX";
type[2] = "NS";
type[3] = "A";
stReturn.email = arguments.emailAddress;
stReturn.diagnostics = StructNew();
</cfscript>
<cftry>
<cfscript>
attributes = dirContext.getAttributes(listgetat(arguments.emailaddress, "2", "@"), type);
atribEnum = attributes.getAll();
stReturn.validMX = 0;// will be overwritten if found
</cfscript>
<cfloop condition="#atribEnum.hasMore()#">
<cfscript>
attribute = atribEnum.next();
stReturn.validEmail = 1;
if(listfirst(attribute.toString(), ":") eq "MX"){
stReturn.validMX = 1;// will be overwritten if found
}
stReturn.diagnostics[listfirst(attribute.toString(), ":")] = listlast(attribute.toString(), ":");
stReturn.message = "Email Ok";
</cfscript>
</cfloop>
<cfcatch type="any">
<cfscript>
stReturn.email = arguments.emailAddress;
stReturn.validEmail = 1;
stReturn.validMX = 0;
stReturn.message = cfcatch.message;
</cfscript>
</cfcatch>
</cftry>
<cfelse>
<cfscript>
stReturn.email = arguments.emailAddress;
stReturn.validEmail = 0;
stReturn.validMX = -1;
stReturn.diagnostics = StructNew();
stReturn.message = "Invalid Email Pattern";
</cfscript>
</cfif>
<cfreturn stReturn>
</cffunction>
Comments
Post a Comment