Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

How Do I Send An Email To Multiple Recipients Without All Email Addresses Being Listed in the To Line?

Use the query attribute of the <cfmail> tag. Doing this will iterate once over the cfmail tag for each row in the query. You must specify the query column that contains the appropriate email address in the to attribute of cfmail.

<!--- query the database to find out who needs the email ---> <cfquery name="getEmailAddresses" dataSource="#theDSN#"> SELECT emailAddress FROM tblUsers </cfquery>

<!--- set up variables --->
<cfset variables.msg = "this is a test message"> <cfset variables.subject = "test subject"> <cfset variables.from = "me@ohMy.com"> <cfset variables.server= "mail.ohMy.com">

<cfmail
from="#variables.from#" subject="#variables.subject#"
query="getEmailAddresses"
to="#emailAddress#"
server="#variables.server#">

#variables.msg#
</cfmail>


This question was written by Todd Sharp.
It was last updated on July 7, 2008 at 10:48:15 AM EDT.

CFML Referenced

<cfquery>
<cfmail>

Categories

Email

Comments

Comment made by Richard Davies on December 21, 2006 at 11:46 AM
Or just use the "bcc" attribute of <cfmail> instead of the "to" attribute. With this approach, there is no need to use a query. All of the addresses are just placed in the bcc attribute.

Although with this approach, there is somewhat of an increased chance that the message might be flagged as spam or junk mail.


Comment made by todd sharp on December 21, 2006 at 2:26 PM
Richard - To is a required attribute - there must be at least one value. Often people will mail to themselves and bcc all other recipients.


Comment made by Michael White on January 4, 2007 at 10:12 AM
I think the point is 1: I didn't know about the query attribute (cool) and 2: if you have a long mailing list you can run a query to get the addresses and send them email one at a time.


Comment made by Jamie Jackson on January 13, 2007 at 12:59 PM
Real mailing list sending code is usually a bit more complicated and robust. Imagine sending mail to thousands of recipients, and it dies in the middle (server failure, timeout, etc.). How do you resume?

Similarly, what if you accidentally call the emailer more than one time, concurrently? Each user will get dupe messages.

To solve these issues, mine usually resemble the following:

[locked: named; can't run this code >1 time concurrently] [query: get recipients who haven't gotten this email yet /] [loop: over query] [cfmail /] [query: flag record as having been sent this email /] [/loop] [/lock]