0

I have some custom audit processes that send emails with sp_send_mail. I discovered recently that testing was sending out emails to everybody because the recipient address was hard coded as a variable value. I'd rather use an Operator so I don't have to alter code moving from one environment to the next. I've googled but this doesn't seem to be a thing unless I'm just using the wrong key words.

What is the proper @recipients value to use an Operator or should I be using a different proc all together?

1 Answer 1

2

You're definitely on the right track but you just need to retrieve the email address of the operator based on the name of the operator like this:

DECLARE @OperatorName sysname = N'OnCallDBAs';

DECLARE @OperatorEmailAddress nvarchar(100) 
    = (SELECT email_address 
       FROM msdb.dbo.sysoperators
       WHERE [name] = @OperatorName);

IF @OperatorEmailAddress IS NOT NULL
BEGIN
    EXEC msdb.dbo.sp_send_dbmail  
        @profile_name = 'Adventure Works Administrator',  
        @recipients = @OperatorEmailAddress,  
        @body = 'The stored procedure finished successfully.',  
        @subject = 'Automated Success Message';
END;

Hope that helps.

1
  • Yup. Nailed it. Commented Sep 19, 2019 at 6:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.