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
    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...
    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...
    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...
    P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
    SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
    BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
    How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
    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...
    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.
    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...
    Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
    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...
    Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
    WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

    SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

    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.
    The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
    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...
    SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
    Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...