Question : populating @recipients value using msdb.dbo.sp_send_dbmail from a database table

Hello

I'm using the stored procedure msdb.dbo.sp_send_dbmail in sql server 2005 to send out emails.

I need to be able to send emails to email addresses stored in a table called emailadd. The msdb.dbo.sp_send_dbmail stored procedure uses the @recipients parameter to guage who the email is sent to, for example:

@recipients = '[email protected]; [email protected],

rather than hard coding these values i want the values to be derived from the emailadd table so that if the email addresses change in the table, the email will go to the right people.

Any ideas?

Thanks

Answer : populating @recipients value using msdb.dbo.sp_send_dbmail from a database table

And just so I might also get a nice little "thats cool" instead of "it was late" from AaronAbend, or even "I learnt something new", what is really cool is being able to loop through each distinct company and provide a single email to all the recipients that belong to that company - all in ONE "select" statement and ONE "exec", no cursors, no loops... while it does use some elements of "classic", don't think you can do that without using the XML version - is it cool yet ?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
create table #test_email_recipients (id int identity, email_address varchar(100), company varchar(100))
 
insert #test_email_recipients (email_address,company) values ('email_1','EE')
insert #test_email_recipients (email_address,company) values ('email_2','EE')
insert #test_email_recipients (email_address,company) values ('email_3','BB')
 
-- if you want to acually run it, need to change your profile_name accordingly... ie change MY_MAIL_PROFILE to whatever is your real profile, and change the above e-mail addresses to something real, and remove the comments from below...
 
declare @sql varchar(max)
select @sql = isnull(@sql,'') + 'exec msdb.dbo.sp_send_dbmail @profile_name=''MY_MAIL_PROFILE'',@recipients='''+
              (select email_address + ';' from #test_email_recipients e where c.company = e.company for xml path('')) + 
              ''',@subject=''Email Listings for '+company+''',@body = ''Dear Staff member of '+company+
              ','+replicate(char(13)+char(10),2)+'You Belong to Company '+company+replicate(char(13)+char(10),2)+
              'Cheers,'+char(13)+char(10)+'Mark Wills'';'+char(13)+char(10)
              from #test_email_recipients c group by company
print @sql
 
--exec (@sql)  -- currerntly less than 500 characters
 
drop table #test_email_recipients
Random Solutions  
 
programming4us programming4us