How do I mail the contents of a form?

One of the most common things a web site may require is a simple "Contact Us" or other form. Normally all you want to do is take the results of the form and email them to the site owner. If you want to quickly deploy a script to do this without all the fancy formatting, you can use the fact that ColdFusion treats form data as a structure. Because of this - there are some simple structure functions we can use to email the contents of the form.

<cfmail to="" from="" subject="Form Foo Submitted" wraptext="80">
<cfloop item="field" collection="#form#">
<cfif field is not "fieldnames">
#field# = #form[field]#

The code snippet above begins with a cfmail tag. Obviously you would change the addresses to match those of the people you want to mail. Next we use cfloop with the item and collection attributes. These tell cfloop to iterate over all the keys of the structure. In this case it will be the fields of the form. Notice that we skip the form field, "fieldnames." This is a special field that ColdFusion creates. It contains all the fields of the form. Since we don't need this, we don't print it.

This question was written by Raymond Camden
It was last updated on July 7, 2008.




comments powered by Disqus