本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 Database Mail 傳送電子郵件訊息
您可以使用 sp_send_dbmail
用量
EXEC msdb.dbo.sp_send_dbmail @profile_name = '
profile_name
', @recipients = 'recipient1@example.com
[;recipient2
; ...recipientn
]', @subject = 'subject
', @body = 'message_body
', [@body_format = 'HTML'], [@file_attachments = 'file_path1
;file_path2
; ...file_pathn
'], [@query = 'SQL_query'
], [@attach_query_result_as_file =0|1
]';
下列是必要參數:
-
@profile_name
– 要從中傳送訊息的 Database Mail 設定檔名稱。 -
@recipients
– 要傳送訊息的電子郵件地址的清單 (以分號分隔)。 -
@subject
– 訊息的主旨。 -
@body
– 訊息的內文。您也可以使用已宣告的變數作為內文。
下列是選用參數:
-
@body_format
– 此參數會搭配宣告變數使用,以 HTML 格式傳送電子郵件。 -
@file_attachments
– 訊息附件清單 (以分號分隔)。檔案路徑必須是絕對路徑。 -
@query
– 要執行的SQL查詢。查詢結果可以作為檔案貼加,也可以包含在訊息內文中。 -
@attach_query_result_as_file
– 是否將查詢結果附加為檔案。設定為 0 表示否,1 表示是。預設值為 0。
範例
下列範例示範如何傳送電子郵件訊息。
範例 傳送訊息給單一收件人
USE msdb GO EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Notifications', @recipients = 'nobody@example.com', @subject = 'Automated DBMail message - 1', @body = 'Database Mail configuration was successful.'; GO
範例 傳送訊息給多位收件人
USE msdb GO EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Notifications', @recipients = 'recipient1@example.com;recipient2@example.com', @subject = 'Automated DBMail message - 2', @body = 'This is a message.'; GO
範例 傳送SQL查詢結果作為檔案附件
USE msdb GO EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Notifications', @recipients = 'nobody@example.com', @subject = 'Test SQL query', @body = 'This is a SQL query test.', @query = 'SELECT * FROM abc.dbo.test', @attach_query_result_as_file = 1; GO
範例 以 HTML 格式傳送訊息
USE msdb GO DECLARE @HTML_Body as NVARCHAR(500) = 'Hi, <h4> Heading </h4> </br> See the report. <b> Regards </b>'; EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Notifications', @recipients = 'nobody@example.com', @subject = 'Test HTML message', @body = @HTML_Body, @body_format = 'HTML'; GO
範例 在資料庫中發生特定事件時使用觸發器傳送訊息
USE AdventureWorks2017 GO IF OBJECT_ID ('Production.iProductNotification', 'TR') IS NOT NULL DROP TRIGGER Purchasing.iProductNotification GO CREATE TRIGGER iProductNotification ON Production.Product FOR INSERT AS DECLARE @ProductInformation nvarchar(255); SELECT @ProductInformation = 'A new product, ' + Name + ', is now available for $' + CAST(StandardCost AS nvarchar(20)) + '!' FROM INSERTED i; EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Notifications', @recipients = 'nobody@example.com', @subject = 'New product information', @body = @ProductInformation; GO