简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM