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

    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...

    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.
    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...
    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...
    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...
    Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
    The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
    Be Among the First 100 to Attend & Receive a Smart Beacon. The Physical Web is an open web project within the Chrome team at Google. Scott Jenson leads a team that is working to leverage the scalability and openness of the web to talk to smart devices. The Physical Web uses bluetooth low energy beacons to broadcast an URL wirelessly using an open protocol. Nearby devices can find all URLs in the room, rank them and let the user pick one from a list. Each device is, in effect, a gateway to a web page. This unlocks entirely new use cases so devices can offer tiny bits of information or simple i...
    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?
    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.
    TechCrunch reported that "Berlin-based relayr, maker of the WunderBar, an Internet of Things (IoT) hardware dev kit which resembles a chunky chocolate bar, has closed a $2.3 million seed round, from unnamed U.S. and Switzerland-based investors. The startup had previously raised a €250,000 friend and family round, and had been on track to close a €500,000 seed earlier this year — but received a higher funding offer from a different set of investors, which is the $2.3M round it’s reporting."
    The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
    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. Over the summer Gartner released its much anticipated annual Hype Cycle report and the big news is that Internet of Things has now replaced Big Data as the most hyped technology. Indeed, we're hearing more and more about this fascinating new technological paradigm. Every other IT news item seems to be about IoT and its implications on the future of digital busines...
    Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
    The Internet of Things needs an entirely new security model, or does it? Can we save some old and tested controls for the latest emerging and different technology environments? In his session at Internet of @ThingsExpo, Davi Ottenheimer, EMC Senior Director of Trust, will review hands-on lessons with IoT devices and reveal privacy options and a new risk balance you might not expect.
    IoT is still a vague buzzword for many people. In his session at Internet of @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, will discuss the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. The presentation will also discuss how IoT is perceived by investors and how venture capitalist access this space. Other topics to discuss are barriers to success, what is new, what is old, and what the future may hold.