Duncan's blog

January 15, 2009

Interesting CFMail whitespace trick

Filed under: Coldfusion — duncan @ 8:47 pm
Tags: , , , , , ,

I’m sure most Coldfusion developers have come across this situation before. When sending an email using <cfmail>, you might have some code that looks vaguely like this:

<cfif sendEmail EQ TRUE>
	<cfif today EQ "Monday">
		<cfloop query="getEmail">
			<cfmail ...>
				#getEmail.salutation# #getEmail.Name#
				
				#getEmail.message#
			</cfmail>
		</cfloop>
	</cfif>
</cfif>

All beautifully indented as it should be. However the recipient gets an email that looks like this:

				Hey Joe
				
				Where you goin' with that gun in your hand?

To get rid of the extra whitespace on each line, you normally have to un-indent the contents of your cfmail:

<cfif sendEmail EQ TRUE>
	<cfif today EQ "Monday">
		<cfloop query="getEmail">
			<cfmail ...>
#getEmail.salutation# #getEmail.Name#

#getEmail.message#
			</cfmail>
		</cfloop>
	</cfif>
</cfif>

Which just looks a bit ugly in amongst all your other code. However I found a neat trick a colleague was using, which I’ve not seen anywhere else.

<cfif sendEmail EQ TRUE>
	<cfif today EQ "Monday">
		<cfloop query="getEmail">
			<cfmail ...>
				#Chr(0)##getEmail.salutation# #getEmail.Name##Chr(13)#
				
				#Chr(0)##getEmail.message##Chr(13)#
			</cfmail>
		</cfloop>
	</cfif>
</cfif>

Chr(0) is the NULL character. However in Coldfusion it returns an empty string, not NULL. Chr(13) is the carriage return character. Together these have the effect of somehow stripping out the leading whitespace.

This only works if you use both Chr(0) at the start and Chr(13) at the end. I tested it with just Chr(0) and just Chr(13), and it didn’t work in either case. Chr(10) might also work, or Chr(13) and Chr(10) together, but I didn’t try testing it.

This trick worked for me on Coldfusion Server 7 and Coldfusion Server 8, but not Coldfusion Server 5. I didn’t test it on other CFML servers such as Railo or Open BlueDragon. Your mileage may vary.

Advertisements

1 Comment »

  1. Works very well in CF8, thank you.

    Comment by Sam — September 24, 2013 @ 4:56 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: