SQLMail - Inserting a variable into @Recipients

I'd like to do something like this:

Select @mailuser = EmailAddress from ContactTable where (criteria blah blah)
exec xp_sendmail @recipients = @mailuser, @subject = 'Hi'

I keep getting a "A recipient was specified ambiguously" error..

I also tried this below thinking that maybe my select statement was the problem, but I get the same error..

Set @mailuser = 'SpecificEmailAddress@SpecificCompany.com'
exec xp_sendmail @recipients = @mailuser, @subject = 'Hi'

Does anyone know how I can use a variable for a parameter in sendmail?

 
Jer995Asked:
Who is Participating?
 
Scott PletcherConnect With a Mentor Senior DBACommented:
I think you will have to use dynamic execution:

DECLARE @sql VARCHAR(2000)
SET @sql = 'EXEC xp_sendmail @recipients=''' + @mailuser + ''', @subject=''Hi'''
EXEC (@sql)
0
 
TroyKCommented:
Jer;

If you go with a dynamic SQL solution, be sure to stringently validate the source of your data, in this case, the ContactTable.

Consider the following script (I changed EXEC to SELECT so that you can see the resulting SQL statement):

-------- BEGIN SQL Script --------
CREATE TABLE ContactTable(
  ArbitraryID int NOT NULL PRIMARY KEY,
  EmailAddress varchar(255)
)
GO

INSERT INTO ContactTable
SELECT 1, 'test@abc.com' UNION ALL
/* Imagine if the SELECT @@Version statement below
   was something harmful, such as 'SHUTDOWN', or DROP TABLE Foo */
SELECT 2, 'i@hacked.you''; SELECT @@Version--'
GO

DECLARE @sql VARCHAR(2000)
DECLARE @mailuser varchar(255)

SELECT @mailuser = EmailAddress FROM ContactTable WHERE ArbitraryID = 1
SET @sql = 'EXEC xp_sendmail @recipients=''' + @mailuser + ''', @subject=''Hi'''
SELECT @sql

SELECT @mailuser = EmailAddress FROM ContactTable WHERE ArbitraryID = 2
SET @sql = 'EXEC xp_sendmail @recipients=''' + @mailuser + ''', @subject=''Hi'''
SELECT @sql
--------------- END SQL Script --------

HTH,
TroyK, MCSD
0
 
Jer995Author Commented:
This worked, Thanks for the help,
Jeremy

Declare @mailuser varchar(255)
Select @mailuser = EmailAddress FROM (table blah blah)where (criteria blah blah)
DECLARE @sql VARCHAR(2000)
SET @sql = 'EXEC xp_sendmail @recipients=''' + @mailuser + ''', @subject=''Hi'''
EXEC (@sql)
0
All Courses

From novice to tech pro — start learning today.