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.
<cfloop item="field" collection="#form#">
<cfif field is not "fieldnames">
#field# = #form[field]#
</cfif>
</cfloop>
</cfmail>
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 at 10:48:51 AM EDT.
CFML Referenced
Categories
Comments
Comment made by Richard Zhu on February 20, 2006 at 4:42 PM
what kind of format do you suggest for insert into database? list, maybe?
Comment made by Raymond Camden on February 21, 2006 at 12:53 PM
Well, I wouldn't use "auto" code like this fdor inserts. I'd write out the insert statement by hand.
Comment made by Michael on March 11, 2006 at 7:40 PM
Sloppy. While this is functional, you would also be emailing your potential client the names of the 'button' and any other hidden fields. Sometimes you might not want to do that. If so, just ignore the loop and put the #form.field# names in as you need.
Its a little more to maintain, but doing it that way is a bit more legible, especially when people submit larger chunks of data to you.
Also, the reply-to="#form.email#" is a nice thing to include in contact form submissions, as the 'sender' of the message will be your mailserver, and I had a lot of trouble explaining to people how to paste the submitted email into the To: field upon hitting reply. If you specify that parameter, then it will be there in *most* email clients.
Comment made by Raymond Camden on March 11, 2006 at 10:27 PM
Michael: Respectfully, I think it is obvious to people that carefully spelling out the exact fields is the best. The intent of this entry was to show a simpler, quicker way to send an entire form, and to reinforce the knowledge that form data can be introspected. I would certainly recommend spelling out the exact fields under normal circumstances, but I feel this sample code here could still be useful to developers.