Welcome!

ColdFusion Authors: Yakov Fain, Maureen O'Gara, Nancy Y. Nee, Tad Anderson, Daniel Kaar

Related Topics: ColdFusion

ColdFusion: Article

Sending E-Mail With ColdFusion

Sending E-Mail With ColdFusion

You've seen it. You've probably done it, too. I'm talking about those Web sites that have a Contact Us link at the bottom of the page with something similar to mailto:[email protected] in the HREF attribute. They're kind of nice...

...and can spare you the burden of opening your e-mail client. They spawn a new message and populate the To: field and perhaps the Subject: field. The mailto: protocol can also be used in the ACTION attribute of the <form> tag. Pretty cool.

Great as the mailto: protocol is, it has shortcomings. Sometimes users don't have their e-mail client software configured correctly, so the link or form submission fails. Anyone who's installed MSIE on more than one occasion can probably attest to this. Plus, users have to confirm every e-mail sent via form submission. That's a necessary annoyance. Also, what if you want to capture more specific information about the user sending the e-mail? Sometimes a Subject: and Message: field just won't cut it.

That's what this article is about - creating an extensible, ColdFusion, Web-based e-mail application that uses only one CF template. This application offers several useful features; you'll see how to add and change them when you find a flavor that meets your needs. All this information will be in a zipped archive on the CFDJ site. Barring minor one-line code changes, the code is ready to use. Here are the features the application will cover:

  • Basic e-mail: Forms-based e-mail we all know and love
  • Handling multiple recipients: Grabbing names and addresses from a database and selecting multiple recipients
  • Keeping user input: Storing submitted info in a database for later crunching
  • Better-looking messages: Adding HTML and graphics to your messages
  • Send attachments: Adding the code for sending attachments

    ColdFusion makes incorporating these and other features quite easy.

    Introducing MailRat
    Figure 1 offers the debut of MailRat, the hippest new e-mail app ever to be powered by ColdFusion (let's not vote, though). As awesome and mind-bending as I've made it out to be, MailRat still consists of the following simple form elements:

  • Fields for your name and e-mail address
  • A SELECT list to choose the recipient's e-mail address(es)
  • A field to enter the topic you want to talk about
  • A text area to input your message
  • A file input field for attachment
  • Radio buttons for creating custom layouts for your messages

    The process is simple. Just enter the required information, then choose Go MailRat!. ColdFusion calls this same file, index.cfm, and changes the banner image on top to confirm that your message has been sent. Figure 2 shows the change in graphics. From the user's perspective there isn't much to it. Let's drill down a bit and see how it's all happening.

    Send e-Mail, Print the Form or Both
    index.cfm performs at least one operation and sometimes two. If the page is loaded for the first time, CF simply displays the MailRat interface. If the form is submitted, index.cfm needs to handle the e-mail operation, then print the interface. Let's assume this is the first time the page has loaded. In that case we'll be looking more at HTML than CFML. Listing 1, which is long but simple, contains the HTML output to create the interface.

    You won't find many surprises in that listing. It's really a form embedded in a couple of nested tables. The CFML in this portion of the document shows up when generating the SELECT list. Here it is up close:

    <select name="TheirEmail"
    style="width:258;" size="3" multiple>
    <CFOUTPUT QUERY="GetContacts">
    <option
    value="#EmailAddress#">#UserName#
    </CFOUTPUT>
    </select>

    The SELECT list is the product of a database query that occurred earlier in the execution. Here is the <CFQUERY>:

    <CFQUERY NAME="GetContacts" DATA-
    SOURCE="ContactDB">
    SELECT UserName, EmailAddress
    From Contacts
    </CFQUERY>

    The SQL inside this statement requests all usernames and corresponding e-mail addresses from the ContactDB data source, which is an MSAccess database. The SELECT list has OPTIONs with usernames as their text and e-mail addresses as their values. Notice, too, that the SELECT list contains the MULTIPLE attribute, i.e., all values of the selected options will be submitted to the server for processing.

    That's all there is to printing the form, except for the graphic at the top. If the MailRat is loading for the first time, ColdFusion displays the default banner. If mail was just sent, CF displays the mail-sent banner. This happens via a simple <CFIF> statement based on the value of the name entered. When the page loads for the first time, the default value of #YourName# is an empty string that cues CF to load the default banner.

    Creating and Validating the Message
    MailRat allows you to choose the type of layout you want the e-mail message to have. I used simple layouts, which basically changes the font family of the text. No reason why you can't go wild and exotic, though. Just make sure whoever receives this has an e-mail client that supports HTML. Most recent clients do, so you should be fine. You also have the option of choosing a file to send as an attachment; just click the button and choose the file from your directory tree. The only drawback is you lose any HTML layout capabilities you may have selected.

    What if you want to send the message to several people? After all, the SELECT list has the MULTIPLE attribute. In this case the code is no different. Remember that the value of #TheirEmail# is a comma-separated string, the same e-mail syntax for sending messages to multiple people. Choosing three people from the list would represent the value of #TheirEmail# to [email protected], [email protected] and person3 @somewhere.com. That's how the string will arrive when the script is called and how it'll be sent, as the value of the TO attribute.

    Notice that clicking on the radio buttons dynamically changes the image to match the mock-up of the font each layout will have. This article is about ColdFusion, but we should go over the JavaScript because there's so much interaction between the two. The image swap occurs when using the following code:

    function swapImg(idx) {
    document ['LayoutImg'].src =
    newImgs[idx].src; }

    It only takes three lines of code - not too bad. This function changes the source of the "Layout" image in the document, which you'll find near the radio button. When called, swapImg() expects an integer that'll reference an Image object with the corresponding JPEG image. Each radio button has the following code:

    onclick="swapImg(some_Integer);"

    Since there are only three images, the integer is either 0, 1 or 2. These integers reference an array element in the JavaScript array newImgs, which is created with a single call to function preload().

    function preload() {
    fExt = '.jpg';
    newImgs = new Array();
    var imgArr = new Array('Boring',
    'OK', 'Fancy');
    for (var i = 0; i
    imgArr.length; i++) {
    newImgs[newImgs.length] = new Image();
    newImgs[newImgs.length - 1].src = imgArr[i] + fExt;
    }
    }

    preload();

    This function preloads the images for the script. Image preloading is the process of downloading images and storing them in the browser cache before they're displayed. This may not seem like a big deal, but each time the user clicks a radio box for the first time, the browser normally makes an HTTP request back to the server to grab the image. If the images are loaded in the cache, the browser already has them and won't need to do the extra legwork.

    The array newImgs contains the Image objects with all the information about each JPEG. By the way, if you want to add more images for preloading, and they're JPEGs in the same folder as the others on the Web server, just add the first name of the image file as a string to the imgArray. For example, adding EvenFancier.jpg to the group changes the array as follows:

    var imgArr = new Array('Boring',
    'OK', 'Fancy', 'EvenFancier');


    Okay, the images are preloaded. The user has filled in the goods and selected an HTML layout option. Choosing Go MailRat! sets things in motion. Before sending everything back to the server, it's a good idea to get JavaScript involved again to make sure the user has provided enough information. Function checkMail() gets the call.

    function checkMail(f) {
    if((f.YourName.value == '') || (f.YourEmail.value == '') ||
    (f.TheirEmail.value == '') || (f.Message.value == '') ||
    (f.YourTopic.value == '')) {
    alert('You must complete all
    fields.');
    return false;
    }
    else if
    (isValidEmail(f.YourEmail.value) &&
    isValidEmail(f.TheirEmail.value)) {
    }
    else { return false; }
    }

    This function first determines if any of the fields (except the optional file attachment field) have been left empty. If so, the user is alerted and the form submission id canceled. Afterwards, checkMail() relies on isValidEmail() to make sure the e-mail address appears valid. I say appears valid because the actual code for validating e-mail addresses, according to the Internet standard, is thousands of characters long. For our purposes, as long as the user enters something, such as [email protected], everything will be fine. If the e-mail address fails this test, the user is again alerted and the submission canceled. Otherwise, it's back to the Web server with the form.

    function isValidEmail(str) {
    str += '';
    namestr = str.substring(0,
    str.indexOf("@")); // before the '@'
    domainstr =
    str.substring(str.indexOf("@")+1,
    str.length); // after the '@'
    if ((namestr.length == 0) ||
    (domainstr.indexOf(".") <= 0) ||
    (domainstr.length == 0) ||
    (domainstr.indexOf("@") != -1)) {
    alert('Hmmm.... "' + str + '"
    appears to be an invalid e-mail address.');
    return false;
    }
    return true;
    }

    Back to ColdFusion
    The form is submitted and index.cfm is called again, but this time things are different. All the CFML we glossed over at the beginning of the article comes into play. CFML uses a single <cfif> statement to determine whether to send e-mail (see Listing 2).

    The deciding factor for sending e-mail is the value of the variable #YourName#. If it's empty, the odds are there's no reason to send mail. As long as #YourName# isn't an empty string, CF will attempt to send e-mail. Once the script has determined that e-mail needs to be sent, it must check if the user uploaded a valid file for use as an attachment. This is done by not only checking the value of #Attachment#, but ensuring that the file exists. If both of the following conditions are true, the attachment will be sent with the plain text message:

    <CFIF #Attachment# NEQ "" AND #File-
    Exists(Attachment)# EQ "True">

    <CFMAIL
    FROM="#YourEmail#"
    TO="#TheirEmail#"
    SUBJECT="#YourTopic#"
    SERVER="pop.serve.com"
    MIMEATTACH="#Attachment#"
    >
    #YourName# wrote:
    #Message#

    <CFMAIL>
    This is the <CFMAIL> tag, which makes our job of sending e-mail ridiculously easy. Though we used only five of the attributes, let's take a look at all of them.

  • TO (required): This attribute expects the recipient's e-mail address(es). You can provide a static value or a ColdFusion variable. Multiple recipient addresses need only be separated by commas.
  • FROM (required): This attribute expects the sender's e-mail address.
  • CC (optional): This attribute can be set to one or more recipients to whom you'd like to send a copy. Can be set static or as a CF variable.
  • SUBJECT (required): This is the subject heading of the message and can be set to a static value or a CF variable.
  • TYPE (optional): This value indicates the MIME type of the message. It can only be set to a value of "HTML." If omitted, the message will be generated as plain text.
  • QUERY (optional): This attribute indicates the name of a database query performed with <cfquery> and can be used to print the results of a query in the message.
  • MAXROWS (optional): Indicates the maximum number of e-mail messages to send.
  • MIMEATTACH (optional): This attribute specifies the name of the path to a file attachment. The value can be static or a ColdFusion variable.
  • GROUP (optional): Used to group a set of query results by column name.
  • STARTROW (optional): Specifies which row to begin with in the query result set (the first row is 1 by default).
  • SERVER (required): Specifies the name or IP address of the SMTP server to contact in order to send the message. If this attribute isn't set, the script uses the SMTP server specified in the ColdFusion Administrator. For more information see the "Configuring a Default SMTP Server" section at the end of this article.
  • PORT (optional): This attribute indicates which TCP/IP port the SMTP listens to for requests. The default is 25.
  • MAILERID (optional): This attribute can specify a string in the SMTP header to identify the application. The default value is Allaire ColdFusion Application Server.
  • TIMEOUT (optional): This indicates the number of seconds to wait for a response from the SMTP server.

    Our <cfmail> tag identifies the sender, recipient, topic, SMTP server and file attachment value. The user provides the script with everything except the SMTP address. What about the message? It's placed between the opening and closing <cfmail></cfmail> tags. Notice there's no HTML, and there is a handful of carriage returns surrounding the #YourName# and #Message# variables. Since the e-mail will be sent as plain text, you have to do the formatting yourself. What you see is what you get.

    If the user hasn't uploaded a valid file attachment, the script uses a slightly different <cfmail> tag (see Listing 3).

    Since there isn't a valid file attached, CF can utilize the HTML attribute of the <cfmail> tag to output a message layout. It all depends on the value of the #Layout# variable, set when the user clicked on the selected radio button. The text in #YourName# and #Message# are still printed as before, but they're wrapped in some HTML.

    Once CF communicates with the SMTP server specified in the SERVER attribute and sends the message, why not store some info about the transaction? The following <cfquery> statement inserts a record into a waiting database.

    <CFQUERY DATASOURCE="ContactDB">
    INSERT INTO SentMessages
    (DateStamp, SenderName, SenderE-
    mail, Recipient, Topic, Message,
    Layout, Attachment)
    VALUES (#CreateODBCDateTime(Now())#, '#Your-
    Name#', '#YourEmail#',
    '#TheirEmail#', '#YourTopic#',
    '#Message#', '#Layout#',
    '#Attachment#')
    </CFQUERY>

    The DATASOURCE attribute is set to ContactDB, an MSAccess database included in the CFDJ download. The embedded SQL statement inserts a new record into the database, storing basically everything the message sender entered, plus the date and time the script ran by calling CFML functions #CreateODBCDateTime(Now())#. If you're interested in the sender's browser information and IP address, you could easily insert the CGI variables #HTTP_USER_AGENT# and #RE-MOTE_SERVER#.

    Wrapping Up
    After the e-mail is sent and the data is stored, the remaining code outputs the mail form to the browser. That's about it. Of course, you can change this application to suit your needs ad infinitum. One of the things you might want to change is the ability to enter any e-mail address without having to choose from a list. No problem. Change the SELECT list to INPUT TYPE=TEXT. Make sure you keep the same name of TheirEmail. Don't worry about validating the recipient's e-mail address before the form is submitted. The JavaScript function checkMail() already does it for you.

    Configuring a Default SMTP Server
    Notice that <CFMAIL> utilizes the SERVER attribute. You can set this value to an SMTP server. However, the CF Administrator makes it shamelessly easy to set a default SMTP server. That way you don't have to use the SERVER attribute every time you want to send mail. Here's how:
    1. Log into your CF Administrator.
    2. Choose Mail under the miscellaneous section.
    3. Enter the address of your SMTP server.
    4. If you want (but probably not), modify the port and time-out settings.
    5. Choose Apply.
    6. If you want to (probably so), choose Verify.

    That's all there is to it. If verification fails, check the SMTP server to confirm that it's available and running.

  • More Stories By Jerry Bradenbaugh

    Jerry Bradenbaugh works as a senior Web developer for Red Oak Technologies, Inc. (www.redoaktech.com). He focuses on robust Web-enabled systems using JavaScript, ColdFusion, Java and database technologies. He is also
    the Webmaster of HotSyte - The JavaScript Resource
    (www.serve.com/hotsyte) and is currently writing a JavaScript book for O'Reilly & Associates, Inc.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    @ThingsExpo Stories
    SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
    SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
    SYS-CON Events announced today that AgilePoint, the leading provider of Microsoft-centric Business Process Management software, will exhibit at SYS-CON's 2nd International @ThingsExpo which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. AgilePoint is the leading provider of Microsoft-based Business Process Management (BPM) software products, has 1,300+ on-premise and cloud deployments in 25+ countries and provides the same advanced BPM feature set as J2EE vendors like IBM and Appian for the Microsoft .NET native environment. AgilePoint customer...
    The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
    SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
    One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, will describe an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people’s real needs and desires.
    SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
    Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
    The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
    Things are being built upon cloud foundations to transform organizations. This CEO Power Panel at 15th Cloud Expo, moderated by Roger Strukhoff, Cloud Expo and @ThingsExpo conference chair, will address the big issues involving these technologies and, more important, the results they will achieve. How important are public, private, and hybrid cloud to the enterprise? How does one define Big Data? And how is the IoT tying all this together?
    We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
    SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
    The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
    SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
    SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
    As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
    The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
    Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
    Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
    From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.