Sending Email from ColdFusion - macromedia COLDFUSION MX 7 Web Application Construction Kit [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

macromedia COLDFUSION MX 7 Web Application Construction Kit [Electronic resources] - نسخه متنی

Ben Forta, Raymond Camden, Leon Chalnick, Angela Buraglia

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید





  • Sending Email from ColdFusion


    ColdFusion's main purpose is to create dynamic, data-driven Web pages. But it also provides a set of email-related tags that let you send email messages that are just as dynamic and data-driven as your Web pages. You can also write ColdFusion templates that check and retrieve email messages, and even respond to them automatically.

    NOTE

    <cfmail> sends standard, Internet-style email messages using the Simple Mail Transport Protocol (SMTP). SMTP isn't explained in detail in this book; for now, all you need to know about SMTP is that it's the standard for sending email on the Internet. Virtually all email programs, such as Netscape, Outlook Express, Eudora, and so on send standard SMTP mail. The exceptions are proprietary messaging systems, such as Lotus Notes or older Microsoft Mail (MAPI-style) clients. If you want to learn more about the underpinnings of the SMTP protocol, visit the World Wide Web Consortium's Web site at www.wc3.org .

    Introducing the <cfmail> Tag


    You can use the <cfmail> tag to send email messages from your ColdFusion templates. After the server is set up correctly, you can use <cfmail> to send email messages to anyone with a standard Internet-style email address. As far as the receiver is concerned, the email messages you send with <cfmail> are just like messages sent via a normal email sending program, such as Netscape, Outlook Express, Eudora, or the like.

    . Text is the default, which means that the message will be sent as a normal, plain-text message. means tha275 tags within the message will be interpreted a274, so you can specify fonts and include images in the email message. See "," later in this chapter.

    wrapText

    Optional. If specified, the text in your email will automatically wrap according to the number passed in. A typical value for wrapText is 72. The default value is to not wrap text.

    mailerID

    Optional. Can be used to specify the X-Mailer header that is sent with the email message. The X-Mailer header is meant to identify which software program was used to send the message. This header is generally never seen by the recipient of the message but can be important to systems in between, such as firewalls. Using the mailerID, you can make it appear as if your message is being sent by a different piece of software. If you find that your outgoing messages are being filtered out when sent to certain users, try using a mailerID that matches another mail client (such as Outlook Express or some other popular, end-user mail client).

    mimeAttach

    Optional. A document on the server's drive that should be included in the mail message as an attachment. This is an older way to specify attachments, maintained for backward compatibility. It's now recommended that you use the <cfmailparam> tag to specify attachments. For details, see "Adding Attachments," later in this chapter.

    charset

    Optional. This specifies the character encoding that will be used in the email. It defaults to the value set in the ColdFusion Administrator.

    spoolEnable

    Optional. Controls whether the email message should be sent right away, before ColdFusion begins processing the rest of the template. The default value is Yes, which means that the message is created and placed in a queue. The actual sending will take place as soon as possible, but not necessarily before the page request has been completed. If you use spoolEnable="No", the message will be sent right away; ColdFusion won't proceed beyond the <cfmail> tag until the sending has been completed. In other words, No forces the mail sending to be a synchronous process; Yes (the default) lets it be an asynchronous process.

    NOTE

    Some additional <cfmail> attributes are introduced later in this chapter (see Table 27.2 in the "Sending Data-Driven Mail" section and Table 27.4 in the "Overriding the Default Mail Server Settings" section).

    Table 27.2. Additional <cfmail> Attributes for Sending Data-Driven Email Messages

    ATTRIBUTE

    PURPOSE

    query

    Optional. A query to use for sending data-driven email. Very similar to the QUERY attribute of the <cfoutput> tag.

    startRow

    Optional. A number that indicates which row of the query to consider when sending data-driven email. The default is to start at the first row. Equivalent to the startRow attribute of the <cfoutput> tag.

    maxRows

    Optional. A maximum number of query rows to consider when sending data-driven email. Equivalent to the maxRows attribute of the <cfoutput> tag.

    group

    Optional. A column name from the query that indicates groups of records. Additional output or processing can occur when each new group is encountered. You can indicate nested groups by providing a comma-separated list of column names. Equivalent to the group attribute of the <cfoutput> tag.

    groupCaseSensitive

    Optional. Whether to consider text case when determining when a new group of records has been encountered in the column(s) indicated by group. Equivalent to the groupCaseSensitive attribute of the <cfoutput> tag.

    Table 27.4. Additional <cfmail> Attributes for Overriding the Mail Server Settings

    ATTRIBUTE

    PURPOSE

    server

    Optional. The host name or IP address of the mail server ColdFusion should use to actually send the message. If omitted, this defaults to the Mail Server setting on the Mail/Mail Logging page of the ColdFusion Administrator. If you are using the Enterprise edition of ColdFusion, a list of mail servers can be provided here.

    port

    Optional. The port number on which the mail server is listening. If omitted, this defaults to the Server Port setting on the Mail/Mail Logging page of the ColdFusion Administrator. The standard port number is 25. Unless your mail server has been set up in a nonstandard way, you should never need to specify the port.

    timeout

    Optional. The number of seconds ColdFusion should spend trying to connect to the mail server. If omitted, this defaults to the Connection Timeout setting on the Mail/Mail Logging page of the ColdFusion Administrator.

    Specifying a Mail Server in the Administrator


    Before you can actually use the <cfmail> tag to send email messages, you need to specify a mail server in the ColdFusion Administrator. This is the mail server with which ColdFusion will interact to actually send the messages generated by your templates.

    To set up ColdFusion to send email, follow these steps:


    1.

    If you don't know it already, find out the host name or IP address for the SMTP mail server ColdFusion should use to send messages. Usually, this is the same server your normal email client program (Outlook Express, Eudora, and so on) uses to send your own mail, so you typically can find the host name or IP address somewhere in your mail client's Settings or Preferences. Often, the host name starts with something such as mail or smtp, as in mail.orangewhipstudios.com .

    2.

    Open the ColdFusion Administrator, and navigate to the Mail page, as shown in Figure 27.1.

    Figure 27.1. Before messages can be sent, ColdFusion needs to know which mail server to use.

    [View full size image]

    3.

    Provide the mail server's host name or IP address in the Mail Server field.

    4.

    Check the Verify Mail Server Connection option.

    5.

    If your mail server operates on a port other than the usual port number 25, provide the port number in the Server Port field. (This usually isn't necessary.)

    6.

    Save your changes by clicking the Submit Changes button.


    TIP

    These settings can be overridden in individual ColdFusion templates by the <cfmail> tag. See the "Overriding the Default Mail Server Settings" section, later in this chapter.

    For more information about the other Mail Server options shown in Figure 27.1, see Chapter 29, "ColdFusion Server Configuration."

    Sending Email Messages


    Sending an email message via a ColdFusion template is easy. Simply code a pair of opening and closing <cfmail> tags, and provide the to, from, and subject attributes as appropriate. Between the tags, type the actual message that should be sent to the recipient.

    Of course, you can use ColdFusion variables and functions between the <cfmail> tags to build the message dynamically, using the # sign syntax you're used to. You don't need to place <cfoutput> tags within (or outside) the <cfmail> tags; your # variables and expressions will be evaluated as if there were a <cfoutput> tag in effect.

    TIP

    As you look through the examples in this chapter, you will find that the <cfmail> tag is basically a specially modified <cfoutput> tag. It has similar behavior (variables and expressions are evaluated) and attributes (group, maxrows, and so on, as listed in Table 27.4).

    Sending a Simple Message

    Listing 27.1 shows how easy it is to use the <cfmail> tag to send a message. The idea behind this template is to provide a simple form for people working in Orange Whip Studios' personnel department. Rather than having to open their normal email client programs, they can just use this Web page. It displays a simple form for the user to type a message and specify a recipient, as shown previously in Figure 27.1. When the form is submitted, the message is sent.

    Listing 27.1. PersonnelMail1.cfmSending Email with ColdFusion


    <!---
    Filename: PersonnelMail1.cfm
    Author: Nate Weiss (NMW)
    Purpose: A simple form for sending email
    --->
    &l275>
    <head>
    <title>Personnel Office Mailer</title>
    <!--- Apply simple CSS formatting to <th> cells --->
    <style>
    th {background:blue;color:white;text-align:right}
    </style>
    </head>
    <body>
    <h2>Personnel Office Mailer</h2>
    <!--- If the user is submitting the Form... --->
    <cfif isDefined("FORM.subject")>
    <!--- We do not want ColdFusion to suppress whitespace here --->
    <cfprocessingdirective suppressWhitespace="No">
    <!--- Send the mail message, based on form input --->
    <cfmail
    subject="#FORM.subject#"
    from="personnel@orangewhipstudios.com"
    to="#FORM.toAddress#"
    bcc="personneldirector@orangewhipstudios.com"
    >This is a message from the Personnel Office:
    #FORM.messageBody#
    If you have any questions about this message, please
    write back or call us at extension 352. Thanks!</cfmail>
    </cfprocessingdirective>
    <!--- Display "success" message to user --->
    <p>The email message was sent.<br>
    By the way, you look fabulous today.
    You should be in pictures!<br>
    <!--- Otherwise, display the form to user... --->
    <cfelse>
    <!--- Provide simple form for recipient and message --->
    <cfform action="#cgi.script_name#" method="post">
    <table cellPadding="2" cellSpacing="2">
    <!--- Table row: Input for Email Address --->
    <tr>
    <th>EMail Address:</th>
    <td>
    <cfinput type="text" name="toAddress" required="yes" size="40"
    message="You must provide an email address.">
    </td>
    </tr>
    <!--- Table row: Input for E-mail Subject --->
    <tr>
    <th>Subject:</th>
    <td>
    <cfinput type="text" name="subject" required="yes" size="40"
    message="You must provide a subject for the email.">
    </td>
    </tr>
    <!--- Table row: Input for actual Message Text --->
    <tr>
    <th>Your Message:</th>
    <td>
    <cftextarea name="messageBody" cols="30" rows="5" wrap="hard"
    required="yes" message="You must provide a message body." />
    </td>
    </tr>
    <!--- Table row: Submit button to send message --->
    <tr>
    <td>&nbsp;</td>
    <td>
    <cfinput type="submit" name="submit" value="Send Message Now">
    </td>
    </tr>
    </table>
    </cfform>
    </cfif>
    </body>
    </html>

    There are two parts to this listing, divided by the large <cfif>/<cfelse> block. When the page is first visited, the second part of the template executes, which displays the form shown in Figure 27.2.

    Figure 27.2. Creating a Web- based mail-sending mechanism for your users is easy.

    When the form is submitted, the first part of the template kicks in, which actually sends the email message with the <cfmail> tag. The message's subject line and "to" address are specified by the appropriate form values, and the content of the message itself is constructed by combining the #FORM.messageBody# variable with some static text. Additionally, each message sent by this template is also sent to the personnel director as a blind carbon copy, via the bcc attribute.

    Around the <cfmail> tag, the <cfprocessingdirective> tag is used to turn off ColdFusion's default white-space-suppression behavior. This is needed in this template because the <cfmail> tag that follows is written to output the exact text of the email message, which includes "newlines" and other white space characters that should be included literally in the actual email message. Without the <cfprocessingdirective> tag, ColdFusion would see the newlines within the <cfoutput> tags as evil white space, deserving to be ruthlessly suppressed.


    For more information about white-space suppression and the <cfprocessingdirective> tag, see the "Controlling White Space" section in Chapter 25, "Improving Performance."

    " section, because white space isn't significant i269.

    Using Friendly Email Addresses

    The email address provided to the to, from, cc, and bcc attributes can be specified as just the email address itself (such as bforta@orangewhipstudios.com), or as a combination of the address and the address's friendly name. The friendly name is usually the person's real-life first and last names.

    To specify a friendly name along with an email address, place the friendly name between double quotation marks, followed by the actual email address between angle brackets. So, instead of


    bforta@orangewhipstudios.com

    you would provide


    "Ben Forta" <bforta@orangewhipstudios.com>

    To provide such an address to the from, to, cc, or bccattribute of the <cfmail> tag, you must double up each double quotation mark shown above, assuming that you are already using double quotation marks around the whole attribute value. So, you might end up with something such as the following:


    <cfmail
    subject="Dinner Plans"
    from=""Nate Weiss" <nweiss@orangewhipstudios.com>"
    to=""Belinda Foxile" <bfoxile@orangewhipstudios.com>">

    If you find the use of the doubled-up double quotation marks confusing, you could surround the fromand to attributes with single quotation marks instead of double quotation marks, which would allow you to provide the double-quotation characters around the friendly name normally, like so:


    <cfmail
    subject="Dinner Plans"
    from='"Nate Weiss" <nweiss@orangewhipstudios.com>'
    to='"Belinda Foxile" <bfoxile@orangewhipstudios.com>'>

    Now, when the message is sent, the "to" and "from" addresses shown in the recipient's email program can be shown with each person's real-life name along with their email address. How the friendly name and email address are actually presented to the user is up to the email client software.

    The version of the PersonnelMail.cfm template shown in Listing 27.2 is nearly the same as the one from Listing 27.1, except that this version collects the recipient's friendly name in addition to their email address. Additionally, this version uses a bit of JavaScript to attempt to pre-fill the email address field based on the friendly name. When the user changes the value in the FirstName or LastName field, the ToAddress field is filled in with the first letter of the first name, plus the whole last name.

    NOTE

    There isn't space to go through the JavaScript code used in this template in detail. It's provided to give you an idea of one place where JavaScript can be useful. Consult a JavaScript reference or online tutorial for details. One good place to look is the JavaScript section of the Reference tab of the Code panel in Dreamweaver.

    Limiting Input

    This version of the form makes it impossible to send messages to anyone outside of Orange Whip Studios, by simply hard-coding the @orangewhipstudios.com part of the email address into the <cfmail> tag itself. Also, it forces the user to select from a short list of Subject lines, rather than being able to type their own Subject, as shown in Figure 27.3.

    Figure 27.3. Web-based forms can make sending email almost foolproof.

    In a real-world application, you probably would make different choices about what exactly to allow users to do. The point is that by limiting the amount of input required, you can make it simpler for users to send consistent email messages, thus increasing the value of your application. This can be a lot of what differentiates Web pages that send mail from ordinary email programs, which can be more complex for users to learn.

    Listing 27.2. PersonnelMail2.cfmProviding Friendly Names Along with Email Addresses


    <!---
    Filename: PersonnelMail2.cfm
    Author: Nate Weiss (NMW)
    Purpose: A simple form for sending email
    --->
    &l275>
    <head>
    <title>Personnel Office Mailer</title>
    <!--- Apply simple CSS formatting to <th> cells --->
    <style>
    th {background:blue;color:white;
    font-family:sans-serif;font-size:12px;
    text-align:right;padding:5px;}
    </style>
    <!--- Function to guess email based on first/last name --->
    <script language="javaScript">
    function guessemail() {
    var guess;
    with (document.mailForm) {
    guess = firstName.value.substr(0,1) + lastName.value;
    toAddress.value = guess.toLowerCase();
    };
    };
    </script>
    </head>
    <!--- Put cursor in FirstName field when page loads --->
    <body <cfif not isDefined("FORM.subject")>
    onLoad="document.mailForm.firstName.focus()"
    </cfif>>
    <!--- If the user is submitting the form... --->
    <cfif isDefined("FORM.subject")>
    <cfset recipEmail = listFirst(FORM.toAddress, "@")
    & "@orangewhipstudios.com">
    <!--- We do not want ColdFusion to suppress whitespace here --->
    <cfprocessingdirective suppressWhitespace="no">
    <!--- Send the mail message, based on form input --->
    <cfmail
    subject="#FORM.subject#"
    from=""Personnel Office" <personnel@orangewhipstudios.com>"
    to=""#FORM.firstName# #FORM.lastName#" <#recipEmail#>"
    bcc="personneldirector@orangewhipstudios.com"
    >This is a message from the Personnel Office:
    #uCase(FORM.subject)#
    #FORM.messageBody#
    If you have any questions about this message, please
    write back or call us at extension 352. Thanks!</cfmail>
    </cfprocessingdirective>
    <!--- Display "success" message to user --->
    <p>The email message was sent.<br>
    By the way, you look fabulous today.
    You should be in pictures!<br>
    <!--- Otherwise, display the form to user... --->
    <cfelse>
    <!--- Provide simple form for recipient and message --->
    <cfform action="#cgi.script_name#" name="mailForm" method="post">
    <table cellPadding="2" cellSpacing="2">
    <!--- Table row: Input for Recipient's Name --->
    <tr>
    <th>Recipient's Name:</th>
    <td>
    <cfinput type="text" name="firstName" required="yes" size="15"
    message="You must provide a first name."
    onChange="guessEmail()">
    <cfinput type="text" name="lastName" required="yes" size="20"
    message="You must provide a first name."
    onChange="guessEmail()">
    </td>
    </tr>
    <!--- Table row: Input for EMail Address --->
    <tr>
    <th>EMail Address:</th>
    <td>
    <cfinput type="text" name="toAddress" required="yes" size="20"
    message="You must provide the recipient's email."
    >@orangewhipstudios.com
    </td>
    </tr>
    <!--- Table row: Input for EMail Subject --->
    <tr>
    <th>Subject:</th>
    <td>
    <cfselect name="subject">
    <option>Sorry, but you have been fired.
    <option>Congratulations! You got a raise!
    <option>Just FYI, you have hit the glass ceiling.
    <option>The company dress code, Capri Pants, and you
    <option>All your Ben Forta are belong to us.
    </cfselect>
    </td>
    </tr>
    <!--- Table row: Input for actual Message Text --->
    <tr>
    <th>Your Message:</th>
    <td>
    <cftextarea name="messageBody" cols="30" rows="5" wrap="hard"
    required="yes" message="You must provide a message body." />
    </td>
    </tr>
    <!--- Table row: Submit button to send message --->
    <tr>
    <td>&nbsp;</td>
    <td>
    <cfinput type="submit" name="submit" value="Send Message Now">
    </td>
    </tr>
    </table>
    </cfform>
    </cfif>
    </body>
    </html>

    Figure 27.4 shows what an email message generated by Listing 27.2 might look like when received and viewed in a typical email client (here, Thunderbird).

    Figure 27.4. Providing a friendly name along with an email address makes for an email message that feels more personal.

    [View full size image]

    Sending Data-Driven Mail


    In the last section, you saw that <cfmail> can be thought of as an extended version of the <cfoutput> tag because ColdFusion variables and expressions are evaluated without the need for an explicit <cfoutput> within the <cfmail>. The similarity between the two tags doesn't end there. They also share attributes specific to the notion of looping over query records. This capability enables you to send data-driven email messages using nearly the same syntax and techniques that you use to output data-drive269 code.

    NOTE

    You may be thinking that a few of these additional attributes aren't really necessary. In today's ColdFusion, you usually can achieve the same results using a <cfloop> tag around a <cfmail> tag to send out multiple messages or using <cfloop> within <cfmail> to include queried information in the message itself. However, the <cfmail> tag appeared in CFML before the <cfloop> tag existed, which is one reason why these attributes exist today.

    Including Query Data in Messages

    By adding a query attribute to the <cfmail> tag, you can easily include query data in the email messages your application sends. Adding the query attribute to <cfmail> is similar to adding query to a <cfoutput> tagthe content inside the tags will repeat for each row of the query.

    Chapter 10, "Creating Data-Driven Pages," for more information about grouping query results.

    Listing 27.3 shows how the <cfmail> tag can be used with the query and group attributes to send data-driven email messages. This example creates a CFML custom tag called <cf_SendOrder Confirmation>, which takes one attribute called orderID, like this:


    <!--- Send Confirmation E-Mail, via Custom Tag --->
    <cf_SendOrderConfirmation
    orderID="3">

    The idea is for the tag to compose an order-confirmation type of email message for the person who placed the order, detailing the items they purchased and when. If you've ever bought something online, you probably received such a confirmation email immediately after placing your order. This custom tag is used in Chapter 28, "Online Commerce," after a user makes an actual purchase.

    Chapter 23, "Building Reusable Components," for information about the CustomTags folder and CFML custom tags in general.

    Listing 27.3. SendOrderConfirmation1.cfmSending a Data-Driven Email Message


    <!---
    Filename: SendOrderConfirmation1.cfm
    Author: Nate Weiss (NMW)
    Purpose: Sends an email message to the person who placed an order
    --->
    <!--- Tag attributes --->
    <cfparam name="ATTRIBUTES.orderID" type="numeric">
    <!--- Retrieve order information from database --->
    <cfquery datasource="ows" name="getOrder">
    SELECT
    c.ContactID, c.FirstName, c.LastName, c.Email,
    o.OrderDate, o.ShipAddress, o.ShipCity,
    o.ShipState, o.ShipZip, o.ShipCountry,
    oi.OrderQty, oi.ItemPrice,
    m.MerchName,
    f.MovieTitle
    FROM
    Contacts c,
    MerchandiseOrders o,
    MerchandiseOrdersItems oi,
    Merchandise m,
    Films f
    WHERE
    o.OrderID = #ATTRIBUTES.orderID#
    AND c.ContactID = o.ContactID
    AND m.MerchID = oi.ItemID
    AND o.OrderID = oi.OrderID
    AND f.FilmID = m.FilmID
    ORDER BY
    m.MerchName
    </cfquery>
    <!--- Re-Query the GetOrders query to find total $ spent --->
    <!--- The DBTYPE="Query" invokes CF's "Query Of Queries" --->
    <cfquery dbtype="query" name="getTotal">
    SELECT SUM(ItemPrice * OrderQty) AS OrderTotal
    FROM GetOrder
    </cfquery>
    <!--- We do not want ColdFusion to suppress whitespace here --->
    <cfprocessingdirective suppressWhitespace="no">
    <!--- Send email to the user --->
    <!--- Because of the GROUP attribute, the inner <CFOUTPUT> --->
    <!--- block will be repeated for each item in the order --->
    <cfmail query="getOrder" group="ContactID" groupCasesensitive="no"
    startrow="1" subject="Thanks for your
    order (Order number #ATTRIBUTES.orderID#)"
    to=""#FirstName# #LastName#" <#Email#>"
    from=""Orange Whip Online Store" <orders@orangewhipstudios.com>"
    >Thank you for ordering from Orange Whip Studios.
    Here are the details of your order, which will ship shortly.
    Please save or print this email for your records.
    Order Number: #ATTRIBUTES.orderID#
    Items Ordered: #recordCount#
    Date of Order: #dateFormat(OrderDate, "dddd, mmmm d, yyyy")#
    #timeFormat(OrderDate)#
    ------------------------------------------------------
    <cfoutput>
    #currentRow#. #MerchName#
    (in commemoration of the film "#MovieTitle#")
    Price: #LSCurrencyFormat(ItemPrice)#
    Qty: #OrderQty#
    </cfoutput>
    ------------------------------------------------------
    Order Total: #lsCurrencyFormat(getTotal.OrderTotal)#
    This order will be shipped to:
    #FirstName# #LastName#
    #ShipAddress#
    #ShipCity#
    #ShipState# #ShipZip# #ShipCountry#
    If you have any questions, please write back to us at
    orders@orangewhipstudios.com, or just reply to this email.
    </cfmail>
    </cfprocessingdirective>

    Chapter 21. However, getting the total via the query of queries feature is a quick and convenient way to obtain the total, using familiar SQL-style syntax.

    ," later in the chapter, for details.

    Now the <cfmail> tag is used to actually send the confirmation message. Because the query attribute is set to the getOrder query, the columns in that query can be freely referred to in the to attribute and the body of the email message itself. Columns specific to each item ordered are referred to within the <cfoutput> block. Columns specific to the order in general are referred to outside the <cfoutput> block, which will be repeated only once because there is only one group of records as defined by the group attribute (that is, all the query records have the same ContactID value).

    Chapter 28, "Online Commerce," after a user makes an actual purchase.

    Sending Bulk Messages

    You can easily use ColdFusion to send messages to an entire mailing list. Simply execute a query that returns the email addresses of all the people the message should be sent to, then refer to the email column of the query in the <cfmail> tag's to attribute.

    Listing 27.4 shows how easy sending a message to a mailing list is. This listing is similar to the Personnel Office Mailer templates from earlier (refer to Listings 27.1 and 27.2). It enables the user (presumably someone within Orange Whip Studios' public relations department) to type a message that will be sent to everyone on the studio's mailing list.

    Listing 27.4. SendBulkEmail.cfmSending a Message to Everyone on a Mailing List

    [View full width]


    <!---
    Filename: SendBulkEmail.cfm
    Author: Nate Weiss (NMW)
    Purpose: Creates form for sending email to everyone on the mailing list
    --->
    &l275>
    <head>
    <title>Mailing List</title>
    <!--- Apply simple CSS formatting to <TH> cells --->
    <style>
    th {background:blue;color:white;
    font-family:sans-serif;font-size:12px;
    text-align:right;padding:5px;}
    </style>
    </head>
    <!--- Put cursor in FirstName field when page loads --->
    <body>
    <!--- Page Title --->
    <h2>Send Message To Mailing List</h2>
    <!--- If the user is submitting the form... --->
    <cfif isDefined("FORM.subject")>
    <!--- Retrieve "mailing list" records from database --->
    <cfquery datasource="ows" name="getList">
    SELECT FirstName, LastName, EMail
    FROM Contacts
    WHERE MailingList = 1
    </cfquery>
    <!--- Send the mail message, based on form input --->
    <cfmail query="getList" subject="#FORM.subject#"
    from=""Orange Whip Studios" <mailings@orangewhipstudios.com>"
    to=""#FirstName# #LastName#" <#EMail#>"
    bcc="personneldirector@orangewhipstudios.com"
    >#FORM.messageBody#
    ----------------------------------------------------
    We respect your privacy here at Orange Whip Studios.
    To be removed from this mailing list, reply to this
    message with the word "Remove" in the subject line.
    ----------------------------------------------------
    </cfmail>
    <!--- Display "success" message to user --->
    <p>The email message was sent.<br>
    By the way, you look fabulous today.
    You should be in pictures!<br>
    <!--- Otherwise, display the form to user... --->
    <cfelse>
    <!--- Provide simple form for recipient and message --->
    <cfform action="#CGI.script_name#" name="mailForm" method="POST">
    <table cellPadding="2" cellSpacing="2">
    <!--- Table row: Input for email Subject --->
    <tr>
    <th>Subject:</th>
    <td>
    <cfinput type="text" name="subject" required="yes" size="40"
    message="You must provide a subject for the email.">
    </td>
    </tr>
    <!--- Table row: Input for actual Message Text --->
    <tr>
    <th>Your Message:</th>
    <td>
    <cftextarea name="messageBody" cols="30" rows="5" wrap="hard"
    required="yes" message="You must provide a message body." />
    </td>
    </tr>
    <!--- Table row: Submit button to send message --->
    <tr>
    <td>&nbsp;</td>
    <td>
    <cfinput type="submit" name="submit"
    value="Send Message Now" onClick="return confirm
    ('Are you sure? This message will be sent to
    everyone on the mailing list. This is your
    last chance to cancel the bulk mailing.')">
    </td>
    </tr>
    </table>
    </cfform>
    </cfif>
    </body>
    </html>

    Like Listing 27.11in the "Creating Automated POP Agents" section of this chapterdemonstrates how ColdFusion can respond to these remove requests.

    Sendin262-Formatted Mail


    As noted in , which enables you to use ordinary HTML tags to add formatting, images, and other media elements to your mail messages.

    The following rules apply:

    • The recipient's email client program must b260 enabled. Most modern email clients, such as Outlook Express or Mozilla Thunderbird, know how to display the contents of email messages a274. However, if the message is read in a program that isn'275 enabled, the user will see the message literally, including the actua267 tags.

    • The mail message should be a well-forme259 document, including . opening and closing &l275>, <head>, and <body> tags.

    • All references to external URLs must be fully qualified, absolute URLs, including the http:// or https://. In particular, this includes the HRef attribute for links and the src attribute for images.


    The version of the <cf_SendOrderConfirmation> tag in attribute. If the tag is called with u274="Yes", a269-formatted version of the confirmation email is sent, including small pictures of each item that was ordered (see is No or is omitted, the email is sent as plain text (as in the previous version). note

    Figure 27.5. As long as the recipient's email program support274, your messages can include formatting, images, and so on.

    Listing 27.5. SendOrderConfirmation2.cfmUsin262 Tags to Format a Mail Message


    <!---
    Filename: SendOrderConfirmation2.cfm
    Author: Nate Weiss (NMW)
    Purpose: Sends an email message to the person who placed an order
    --->
    <!--- Tag attributes --->
    <cfparam name="ATTRIBUTES.orderID" type="numeric">
    <cfparam name="ATTRIBUTES.u274" type="boolean" default="yes">
    <!--- Local variables --->
    <cfset imgSrcPath = "http://#CGI.HTTP_HOST#/ows/images">
    <!--- Retrieve order information from database --->
    <cfquery datasource="ows" name="getOrder">
    SELECT
    c.ContactID, c.FirstName, c.LastName, c.Email,
    o.OrderDate, o.ShipAddress, o.ShipCity,
    o.ShipState, o.ShipZip, o.ShipCountry,
    oi.OrderQty, oi.ItemPrice,
    m.MerchName, m.ImageNameSmall,
    f.MovieTitle
    FROM
    Contacts c,
    MerchandiseOrders o,
    MerchandiseOrdersItems oi,
    Merchandise m,
    Films f
    WHERE
    o.OrderID = #ATTRIBUTES.OrderID#
    AND c.ContactID = o.ContactID
    AND m.MerchID = oi.ItemID
    AND o.OrderID = oi.OrderID
    AND f.FilmID = m.FilmID
    ORDER BY
    m.MerchName
    </cfquery>
    <!--- Display an error message if query returned no records --->
    <cfif getOrder.recordCount eq 0>
    <cfthrow message="Failed to obtain order information."
    detail="Either the Order ID was incorrect,
    or order has no detail records.">
    <!--- Display an error message if email blank or not valid --->
    <cfelseif (getOrder.Email doesn't contain "@")
    OR (getOrder.Email doesn't contain ".")>
    <cfthrow message="Failed to obtain order information."
    detail="Email addresses need to have an @
    sign and at least one 'dot'.">
    </cfif>
    <!--- Query the GetOrders query to find total $$ --->
    <cfquery dbtype="query" name="getTotal">
    SELECT SUM(ItemPrice * OrderQty) AS OrderTotal
    FROM GetOrder
    </cfquery>
    <!--- *** If we are sendin262-Formatted Email *** --->
    <cfif ATTRIBUTES.u274>
    <!--- Send Email to the user --->
    <!--- Because of the GROUP attribute,
    the inner <CFOUTPUT> --->
    <!--- block will be repeated for each
    item in the order --->
    <cfmail query="getOrder" group="ContactID"
    groupCasesensitive="No"
    subject="Thanks for your order (Order number
    #ATTRIBUTES.orderID#)"
    to=""#FirstName# #LastName#" <#Email#>"
    from=""Orange Whip Online Store" <orders@
    orangewhipstudios.com>"
    type="HTML">
    &l275>
    <head>
    <style type="text/css">
    body {font-family:sans-serif;font-size:12px;color:navy}
    td {font-size:12px}
    th {font-size:12px;color:white;
    background:navy;text-align:left}
    </style>
    </head>
    <body>
    <h2>Thank you for your Order</h2>
    <p><b>Thank you for ordering from
    <a >Orange Whip Studios</a>.</b><br>
    Here are the details of your order, which will ship shortly.
    Please save or print this email for your records.<br>
    <p>
    <strong>Order Number:</strong> #ATTRIBUTES.orderID#<br>
    <strong>Items Ordered:</strong> #recordCount#<br>
    <strong>Date of Order:</strong>
    #dateFormat(OrderDate, "dddd, mmmm d, yyyy")#
    #timeFormat(OrderDate)#<br>
    <table>
    <cfoutput>
    <tr valign="top">
    <th colspan="2">
    #MerchName#
    </th>
    </tr>
    <tr>
    <td>
    <!--- If there is an image available... --->
    <cfif ImageNameSmall neq ">
    <img src="#imgSrcPath#/#ImageNameSmall#"
    width="50" height="50" border="0">
    </cfif>
    </td>
    <td>
    <em>(in commemoration of the film "#MovieTitle#")</em><br>
    <strong>Price:</strong> #lsCurrencyFormat(ItemPrice)#<br>
    <strong>Qty:</strong> #OrderQty#<br>&nbsp;<br>
    </td>
    </tr>
    </cfoutput>
    </table>
    <p>Order Total: #lsCurrencyFormat(getTotal.OrderTotal)#<br>
    <p><strong>This order will be shipped to:</strong><br>
    #FirstName# #LastName#<br>
    #ShipAddress#<br>
    #ShipCity#<br>
    #ShipState# #ShipZip# #ShipCountry#<br>
    <p>If you have any questions, please write back to us at
    <a href="orders@orangewhipstudios.com">orders@orangewhipstudios.com</a>,
    or just reply to this email.<br>
    </body>
    </html>
    </cfmail>
    <!--- *** If we are NOT sendin262-Formatted Email *** --->
    <cfelse>
    <!--- We do not want ColdFusion to suppress whitespace here --->
    <cfprocessingdirective suppressWhitespace="no">
    <!--- Send email to the user --->
    <!--- Because of the GROUP attribute, the inner <CFOUTPUT> --->
    <!--- block will be repeated for each item in the order --->
    <cfmail query="getOrder" group="ContactID" groupCasesensitive="No"
    subject="Thanks for your order (Order number #ATTRIBUTES.OrderID#)"
    to=""#FirstName# #LastName#" <#Email#>"
    from=""Orange Whip Online Store" <orders@orangewhipstudios.com>"
    >Thank you for ordering from Orange Whip Studios.
    Here are the details of your order, which will ship shortly.
    Please save or print this email for your records.
    Order Number: #ATTRIBUTES.orderID#
    Items Ordered: #recordCount#
    Date of Order: #dateFormat(OrderDate, "dddd, mmmm d, yyyy")#
    #timeFormat(OrderDate)#
    ------------------------------------------------------
    <cfoutput>
    #currentRow#. #MerchName#
    (in commemoration of the film "#MovieTitle#")
    Price: #lsCurrencyFormat(ItemPrice)#
    Qty: #OrderQty#
    </cfoutput>
    ------------------------------------------------------
    Order Total: #lsCurrencyFormat(getTotal.OrderTotal)#
    This order will be shipped to:
    #FirstName# #LastName#
    #ShipAddress#
    #ShipCity#
    #ShipState# #ShipZip# #ShipCountry#
    If you have any questions, please write back to us at
    orders@orangewhipstudios.com, or just reply to this email.
    </cfmail>
    </cfprocessingdirective>
    </cfif>

    . If so, <cfmail> is used with type="HTML" to send a269-formatted message. If not, a separate <cfmail> tag is used to send a plain-text message. Note that the <cfprocessingdirective> tag is needed only around the plain-text version of the message becaus260 isn't sensitive to white space.

    As already noted, a fully qualified URL must be provided for images to be correctly displayed in email messages. To make this easier, a variable called imgSrcPath is defined at the top of the template, which will always hold the fully qualified URL path to the ows/images folder. This variable can then be used in the src attribute of any <img> tags within the message. For instance, assuming that you are visiting a copy of ColdFusion server on your local machine, this variable will evaluate to something such as http://localhost/ows/images/.

    Appendix D, "Special ColdFusion Variables and Result Codes."

    In addition, type="HTML" only if you know the recipient is using a269-enabled email client program.

    Adding Custom Mail Headers


    All SMTP email messages contain a number of mail headers, which give Internet mail servers the information necessary to route the message to its destination. Mail headers also provide information used by the email client program to show the message to the user, such as the message date and the sender's email address.

    ColdFusion allows you to add your own mail headers to mail messages, using the <cfmailparam> tag.

    TIP

    You can see what these mail headers look like by using an ordinary email client program. For instance, in Outlook Express, highlight a message in your Inbox, select Properties from the File menu, and then click the Details tab.

    Introducing the <cfmailparam> Tag

    ColdFusion provides a tag called <cfmailparam> that can be used to add custom headers to your mail messages. It also can be used to add attachments to your messages, which is discussed in the next section. The <cfmailparam> tag is allowed only between opening and closing <cfmail> tags. tex275).

    contentID

    Specifies an identifier for the attached file. This is used to identify the file that an img or other tag in the email uses.

    disposition

    This attribute describes how the file should be attached to the email. There are two possible values, attachment and inline. The default, attachment, means the file is added as attachment. If you specify inline, the file will be included in the message.

    Adding Attachments


    As noted in Table 27.3, you can also use the <cfmailparam> tag to add a file attachment to a mail message. Simply place a <cfmailparam> tag between the opening and closing <cfmail> tags, specifying the attachment's filename with the file attribute. The filename must be provided as a fully qualified file-system path, including the drive letter and volume name. It can't be expressed as a relative path or URL.

    NOTE

    The filename you provide for a file must point to a location on the ColdFusion server's drives (or a location on the local network). It can't refer to a location on the browser machine. ColdFusion has no way to grab a document from the browser's drive. If you want a user to be able to attach a file to a <cfmail> email, you first must have them upload the file to the server. See Chapter 34, "Interacting with the Operating System," for details about file uploads.

    TIP

    The attachment doesn't have to be in your Web server's document root. In fact, you might want to ensure that it's not, if you want people to be able to access it only via email, rather than via the Web.

    To add a Word document called BusinessPlan.doc as an attachment, you might include the following <cfmailparam> tag between your opening and closing <cfmail> tags:


    <!-- Attach business plan document to message --->
    <cfmailparam
    file="c:\OwsMailAttachments\BusinessPlan.doc">

    TIP

    To add multiple attachments to a message, simply provide multiple <cfmailparam> tags, each specifying one file.

    NOTE

    As noted in Table 27.1, you also can use the older mimeattach attribute of the <cfmail> tag to add an attachment, instead of coding a separate <cfmailparam> tag. However, it's recommended that you use <cfmailparam> instead because it's more flexible (it allows you to add more than one attachment to a single message).

    Overriding the Default Mail Server Settings


    Earlier in this chapter, you learned about the settings on the Mail/Mail Logging page of the ColdFusion Administrator (refer to Figure 27.1). These settings tell ColdFusion which mail server to communicate with to send the messages that your templates generate. In most situations, you can simply provide these settings once, in the ColdFusion Administrator, and forget about them. ColdFusion will use the settings to send all messages.

    However, you might encounter situations in which you want to specify the mail server settings within individual <cfmail> tags. For instance, your company might have two mail servers set up, one for bulk messages and another for ordinary messages. Or you might not have access to the ColdFusion Administrator for some reason, perhaps because your application is sitting on a shared ColdFusion server at an Internet service provider (ISP).

    To specify the mail server for a particular <cfmail> tag, add the server attribute, as explained in Table 27.4. You also can provide the port and timeout attributes to completely override all mail server settings from the ColdFusion Administrator.

    NOTE

    If you need to provide these attributes for your <cfmail> tags, consider setting a variable called APPLICATION.mailServer in your Application.cfc file and then specifying server="#APPLICATION.mailServer#" for each <cfmail> tag.

  • / 281