Using CFMAIL's server attribute to store additional information

Did you know that CFMAIL’s server attribute allows you to pass in the username, password, and port information as well? Why would you do that? Let’s say you are building code for an application where the port setting may not exist. Your server is set to mypop.com. To conditionally add the port you could do something like this: <cfif application.mailport neq ""> <cfset application.mailserver = application.mailserver & ":" & application.mailport> </cfif>

So a mailserver value of mypop.com and a port of 25 would end up with an application.mailserver value of mypop.com:25.

The same can be done with the username and password. The syntax you would use in the server setting would be:

username:password@server

So a practical example of this would look like so:

<cfif application.mailusername neq ""> <cfset application.mailserver = application.mailusername & ":" & application.mailpassword & "@" & application.mailserver> </cfif>

Obviously this only works if the password exists as well.

So all in all this helps a lot. I want to thank Andrew Penhorwood for reminding me of this. I included it in the latest build of Lighthouse Pro. Unfortunately, if you want to build truly robust code to handle all situations, even those where you don’t need a mail server specified, you have a problem. If you try to do this:

<cfmail server="" ....>

You will get an error. This means you need to wrap your cfmail tags in silly CFIF conditionals:

<cfif len(application.mailserver)> <cfmail server="#application.mailserver#" to="#application.adminemail#" from="#application.adminemail#" subject="Error in Lighthouse Pro" type="html">#mailbody#</cfmail> <cfelse> <cfmail to="#application.adminemail#" from="#application.adminemail#" subject="Error in Lighthouse Pro" type="html">#mailbody#</cfmail> </cfif>

It would probably be best to build a simple CFC that could handle your mailing for you. Hopefully Scorpio will address this, although most folks don’t have to worry about writing their code like this.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments