Skip to main content
Participating Frequently
May 20, 2010
Question

Sending templated email with CFMAIL

  • May 20, 2010
  • 2 replies
  • 2416 views

i am needing to send multiple types of emails in my scripts.  however, all of these emails will use the same format, just have different content.

what i was wanting to do was create like a "template.cfm" file that would contain the template, and when loaded, i could populate variables in that markup and use it as the content for a CFMAIL.

i thought about using CFFILE to load the file into a variable, but then i don't know how to swap out the variables.  i also thought about using a CFINCLUDE inside the CFMAIL tag, but i don't know if that is possible.

any recommendations on how to do this?

thanks,

jz

This topic has been closed for replies.

2 replies

Inspiring
May 20, 2010

You might create a custom tag or ColdFusion component (CFC).  The code below is not tested and intended as a quick demo.  This is a custom tag that would allow you to specify to, from, subject, and message for your email.  Using a CFC is another option.

<!--- contentes of mail_template.cfm custom tag --->
<cfparam name="attributes.to" default="customer@example.com" />
<cfparam name="attributes.from" default="service@example.com" />
<cfparam name="attributes.message" default="" />
<cfparam name="attributes.subject" default="" />

<cfmail to="#attributes.to#" from="#attributes.from#" subject="#attributes.subject#" type="html">

<html>
<head>
     <style type="text/css">body { font-family: arial, sans-serif; font-size: 12pt }</style>
</head>

<body>

     Dear Customer,

     Your message is: <cfoutput>#HtmlEditFormat(attributes.message)#</cfoutput>

</body>

</html>

</cfmail>

Inspiring
May 20, 2010

Put your mail template into a .cfm file.  make the template a variable  that includes placeholders for your variables - something like Variable1, Variable2 etc.

Cfinclude that .cfm file.  Use the replace function with the template variable to get the other variables into the proper place.  Then use that modified variable in your cfmail tag.

Participating Frequently
May 20, 2010

if i would use a CFSET to assign values to the variable names in the CFINCLUDE file, would i have to still do the replace?

Inspiring
May 20, 2010

You have to do the replace.