Saturday, May 21, 2005

Insert Picture into Email

How to insert picture in email body when using CFMAIL ?

First, you must be running MX6.1 with updater installed or MX7.

When using inline images inside an email, you need to use a Content ID to reference it instead of the file name. This Content ID needs to be globally unique - meaning that there should never be a duplicate Content ID used, ever. To assist in this, you can use a CID function I wrote to create such a value.

function CID()
return LCase(CreateUUID() & "@" & FormatBaseN(RandRange(0,65535),16) &
"@" & ListFirst(CGI.Server_Name,"."));

Okay, now let's assign a Content ID to an image. You would do these same steps for every image. Code references in this email assumes a <cfscript> block except for the cfmail tag.

CFSET ImgLogo=CID();

Now you want to create your HTML. When referencing the image, reference the CID value with a "cid:" prefix. Keep in mind that using two double-quotes escapes it so you can embed quotes inside variables instead of using Chr(34). Another option of generating your email body is to simply generate it normally as HTML but with a cfsavecontent tag wrapped around it so any generated HTML will be stored in a variable instead of being sent to the browser.

EmailBody="<html><body><img src=""cid:#ImgLogo#""></body></html>";

Now using the cfsavecontent tag.
<cfsavecontent variable="EmailBody">
<img src="cid:#ImgLogo#">

Now we're ready to execute our CFMAIL tag.

<cfmail to="" from="" subject="Test" type="HTML">
<cfmailparam file="RootDir#/logo.gif" type="image/jpeg" contentid="#ImgLogo#" disposition="attachment">

I found that it's best to include the images at the end of the email body, otherwise MX will add extra line feeds at the top unless you put everything in one big long line


Post a Comment

<< Home