Skip to content

Instantly share code, notes, and snippets.

@mjclemente
Forked from JamoCA/isEmailDomainValid.cfm
Last active January 30, 2018 21:35
Show Gist options
  • Save mjclemente/bb4b9a97f5ccc9d9d63841bc64efa0b4 to your computer and use it in GitHub Desktop.
Save mjclemente/bb4b9a97f5ccc9d9d63841bc64efa0b4 to your computer and use it in GitHub Desktop.
ColdFusion UDF to validate if an email address' MX record exists.
<!--- NOTE: This technique is not 100% accurate because some DNS servers don't allow MX queries or may be slow to respond,
but this will identify addresses that are potentially bad or suspicious. --->
<!--- some elements are incorporated from @pfreitag's post here: https://www.petefreitag.com/item/487.cfm --->
<cfscript>
public boolean function isEmailDomainValid( required string email, string dnsServer = '8.8.8.8', numeric timeout = 2000, numeric retries = 1 ){
var mxRecords = [];
var emailDomain = email.listLast( '@' ).trim();
if ( !isValid( 'email', email ) )
return false;
var env = CreateObject( 'java', 'java.util.Hashtable' );
env.put( 'java.naming.factory.initial', 'com.sun.jndi.dns.DnsContextFactory' );
env.put( 'java.naming.provider.url', 'dns://#dnsServer#' );
env.put( 'com.sun.jndi.dns.timeout.initial', timeout );
env.put( 'com.sun.jndi.dns.timeout.retries', retries );
var dirContext = CreateObject( 'java', 'javax.naming.directory.InitialDirContext' );
dirContext.init( env );
try {
var records = dirContext.getAttributes( emailDomain, [ 'MX' ] ).get( 'MX' ).getAll();
while( records.hasMore() ) {
var record = records.next().ToString();
mxRecords.append( record );
}
} catch ( any e ){
//if there are no mx records, the lookup fails
return false;
}
return mxRecords.len();
}
</cfscript>
<cfoutput>
<cfsavecontent variable="Emails">test@#CGI.Server_Name#
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
test@aol
[email protected]
[email protected]
[email protected]
[email protected]
test@invalid_email</cfsavecontent>
<style type="text/css">
li.no {color:##f30;}
li.yes {color:##3c0;}
</style>
<h2>Validate Email Address MX Records</h2>
<ol>
<cfloop array="#ListToArray(Emails,chr(10))#" index="thisEmail">
<cfset Start = GetTickCount()><cfset Status = isEmailDomainValid(trim(thisEmail))><cfset TheTime = GetTickCount()-Start>
<li class="#lcase(yesnoformat(Status))#">#trim(ThisEmail)# = #Status# (#numberformat(TheTime)#ms)</li>
</cfloop>
</ol>
</cfoutput>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment