搭配 Linux 上 SQL Server Agent 的 Database Mail 和電子郵件警示

適用於:SQL Server - Linux

本文說明如何設定 Database Mail 並將其與 Linux 上的 SQL Server Agent (mssql-server-agent) 搭配使用。

1.啟用 Database Mail

USE master;
GO

sp_configure 'show advanced options', 1;
GO

RECONFIGURE WITH OVERRIDE
GO

sp_configure 'Database Mail XPs', 1;
GO

RECONFIGURE;
GO

2.建立新帳戶

EXECUTE msdb.dbo.sysmail_add_account_sp @account_name = 'SQLAlerts',
    @description = 'Account for Automated DBA Notifications',
    @email_address = 'sqlagenttest@example.com',
    @replyto_address = 'sqlagenttest@example.com',
    @display_name = 'SQL Agent',
    @mailserver_name = 'smtp.example.com',
    @port = 587,
    @enable_ssl = 1,
    @username = 'sqlagenttest@example.com',
    @password = '<password>';
GO

3.建立預設設定檔

EXECUTE msdb.dbo.sysmail_add_profile_sp
    @profile_name = 'default',
    @description = 'Profile for sending Automated DBA Notifications';
GO

4.將 Database Mail 帳戶新增至 Database Mail 設定檔

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'default',
    @principal_name = 'public',
    @is_default = 1;
GO

5.將帳戶新增至設定檔

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'default',
    @account_name = 'SQLAlerts',
    @sequence_number = 1;
GO

6.傳送測試電子郵件

您可能必須移至電子郵件用戶端,並啟用 [允許較不安全的用戶端傳送郵件] 選項。 並非所有用戶端都會將 Database Mail 辨識為電子郵件精靈。

EXECUTE msdb.dbo.sp_send_dbmail
    @profile_name = 'default',
    @recipients = 'recipient-email@example.com',
    @subject = 'Testing DBMail',
    @body = 'This message is a test for DBMail'
GO

7.使用 mssql-conf 或環境變數來設定 Database Mail 設定檔

您可以使用 mssql-conf 公用程式或環境變數來註冊您的 Database Mail 設定檔。 在此情況下,我們將呼叫設定檔 default

  • 透過 mssql-conf 進行設定:

    sudo /opt/mssql/bin/mssql-conf set sqlagent.databasemailprofile default
    
  • 透過環境變數設定:

    MSSQL_AGENT_EMAIL_PROFILE=default
    

8.設定 SQL Server Agent 作業通知的運算子

EXEC msdb.dbo.sp_add_operator
    @name = N'JobAdmins',
    @enabled = 1,
    @email_address = N'recipient-email@example.com',
    @category_name = N'[Uncategorized]';
GO

9.「代理程式測試作業」成功時傳送電子郵件

EXEC msdb.dbo.sp_update_job
    @job_name = 'Agent Test Job',
    @notify_level_email = 1,
    @notify_email_operator_name = N'JobAdmins'
GO