Ask a Jedi: Emailing CFCHART

Abhishek asks:

I've a doubt, what i'm doing is that i'm generating chart using cfchart inside cfsavecontent and then i want to send the entire data of the cfsavecontent in mail using cfmail. Mail is working fine but unable to get the chart in the mail instead of that there comes red x image and in view source it is showing a path somewhat like this /CFID/GraphData.cfm?graphCache=wc5. Please give some solution.

Well, don’t forget that, by default, when you use cfhcart you are going to get object/embed tags pointing back to your server to load a dynamic Flash SWF file. I’d be surprised if any mail client would render Flash client in context.

You could switch to PNG of course. If you use HTML email you could then embed that image in one of two ways. One way would be to save the PNG to your web server. Your HTML email would then simply point to your web server. If the email is viewed offline then the image won’t load, but that’s probably not a huge concern.

The other option is to the cfmailparam tag and an inline image. I had never used this before but the docs made it fairly simple. Here is a complete example and then I’ll go over the salient points:

<cfchart format="png" name="chart"> <cfchartseries type="pie"> <cfchartdata item="1Q Sales" value="500" /> <cfchartdata item="2Q Sales" value="400" /> <cfchartdata item="3Q Sales" value="700" /> <cfchartdata item="4Q Sales" value="200" /> </cfchartseries> </cfchart>

<cfset savedFile = getTempFile(getTempDirectory(),”foremail”) & “.png”> <cfset fileWrite(savedFile,chart)>

<cfoutput>#savedFile#</cfoutput> <cfmail to=”ray@camdenfamily.com” from=”ray@camdenfamily.com” subject=”Sales” type=”html”> <cfmailparam contentID=”img1” file=”#savedFile#” disposition=”inline”>

<h2>Sales Figures</h2> <p> Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. </p>

<img src=”cid:img1” />

</cfmail> </code>

The chart (in this case a hard coded chart) is stored into a variable using the name attribute. I save the file in the temp directory. The cfmailparam tag points to the file and provides an ID that the HTML can refer to later. Notice the image tag uses cid: instead of http:

I did test this just to make sure it actually worked, and it did (which always tends to surprise me!):

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments