Search code examples
sql-servert-sql

How do you send email with TSQL using a Agent Operator instead of an email address?


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?


Solution

  • 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.