« Updates to EmailParse.CFC: Quoted-printable parsing and Received header | Main | Unit testing (and beers) with the Boston CFUG »

Spam/RBL lookup added to EmailParse.CFC

I made yet another update to EmailParse.CFC last week while I was working in the code for other reasons: I've added spam lookup on the sender's IP address courtesy of SpamHaus.org.

There are two parts to the functionality which performs the RBL lookup. First, we look through the Received: headers to find the earliest one which contains a sending IP. Second, we take that IP address, reformat it a little, and send it off to zen.spamhaus.org to see if it's listed in their RBL.

Each of these steps is encapsulated in two functions:


<cffunction name="senderIPIsBlacklisted" output="true" hint="Checks an IP address against blacklist services">
	<cfargument name="BLServer" default="zen.spamhaus.org" required="no" />
	<cfset var index = '' />
	<cfset var thisHeader = '' />
	<cfset var REIPString = '(((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))' />
	<cfset var IPAddress = '' />
	
	<!--- Extract the sending IP from the email headers --->
	<cfloop index="index" from="#ListLen(this.received, '|')#" to="1" step="-1">
		<cfset thisHeader = ListGetAt(this.received, index, '|') />
		<cfif thisHeader contains 'from' and thisHeader contains 'by' and ReFind(REIPString, thisHeader)>
			<cfset IPAddress = ReMatch(REIPString, thisHeader) />
			<cfset IPAddress = IPAddress[1] />
			<cfbreak />
		</cfif>
	</cfloop>
	
	<cfreturn checkBL(IPAddress, ARGUMENTS.BLServer) />
</cffunction>

<cffunction name="checkBL" output="true" hint="Checks an IP address against blacklist services">
	<cfargument name="IPAddress" required="yes" />
	<cfargument name="BLServer" default="zen.spamhaus.org" required="no" />
	<cfset var index = '' />
	<cfset var IPPayload = '' />
	<cfset var oBLCheck = '' />
	
	<!--- Reverse the IP address and prepend it to the BL Server --->
	<cfloop index="index" from="#ListLen(ARGUMENTS.IPAddress, '.')#" to="1" step="-1">
		<cfset IPPayload = IPPayload & ListGetAt(ARGUMENTS.IPAddress, index, '.') & '.' />
	</cfloop>
	<cfset IPPayload = IPPayload & ARGUMENTS.BLServer />
	
	<!--- Test the value against the blacklist --->
	<cfset oBLCheck = CreateObject("java", "java.net.InetAddress") />
	<cftry>
		<cfset oBLCheck = oBLCheck.getByName(IPPayload) />
		<cfif Len(oBLCheck.getHostName())>
			<cfreturn true />
		<cfelse>
			<cfreturn false />
		</cfif>
		<!--- If there's an error, it's probably because the IP isn't listed on the BL --->
		<cfcatch><cfreturn false /></cfcatch>
	</cftry>
	
</cffunction>

As always, you can download EmailParse.CFC from my projects section.

Post a comment


Type the characters you see in the picture above.