首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

SQL Server 郵件功能完整指南:xp_startmail 到 xp_sendmail 參數詳解

     編輯:關於SqlServer

啟動與停止 SQL Mail

-- 啟動 (參數可選)
EXEC xp_startmail @user, @password

-- 或企業管理員 → Support Services → SQL Mail → 右鍵 Start

-- 停止
EXEC xp_stopmail

發送郵件:xp_sendmail 完整參數

EXEC xp_sendmail
    @recipients = 'recipients[;...n]'        -- 必填,收件人以分號分隔
    [, @message = 'message']                 -- 郵件內文
    [, @query = 'query']                     -- 查詢結果附件 (除 inserted/deleted 表外任意物件)
    [, @attachments = 'attachments']         -- 檔案附件
    [, @copy_recipients = 'cc[;...n]']       -- 副本
    [, @blind_copy_recipients = 'bcc[;...n]']-- 密件副本
    [, @subject = 'subject']                 -- 主旨
    [, @type = 'type']                       -- 郵件類型
    [, @attach_results = 'attach_value']     -- 查詢結果作附件發送
    [, @no_output = 'output_value']          -- 抑制輸出
    [, @no_header = 'header_value']          -- 不發送查詢結果欄位名
    [, @width = width]                       -- 輸出寬度
    [, @separator = 'separator']             -- 欄位分隔字元
    [, @echo_error = 'echo_value']           -- 回傳錯誤
    [, @set_user = 'user']                   -- 查詢執行用戶 (預設 Guest)
    [, @dbuse = 'database']                  -- 查詢使用資料庫 (預設預設資料庫)

參數速查表

參數說明
@recipients收件人,分號分隔,必填
@message郵件本文文字
@query執行查詢並將結果附件化
@attachments檔案路徑,多檔分號分隔
@copy_recipientsCC 副本收件人
@blind_copy_recipientsBCC 密件副本
@subject郵件主旨
@attach_results查詢結果作附件 (TRUE/FALSE)
@no_header隱藏查詢結果標題列
@set_user查詢執行安全性內容
@dbuse查詢上下文資料庫

讀取郵件:xp_readmail

EXEC xp_readmail
    [@msg_id = 'message_number']
    [, @type = 'type' OUTPUT]
    [, @peek = 'peek']                       -- 僅預覽不標記已讀
    [, @suppress_attach = 'suppress_attach']
    [, @originator = 'sender' OUTPUT]
    [, @subject = 'subject' OUTPUT]
    [, @message = 'message' OUTPUT]
    [, @recipients = 'recipients[;...n]' OUTPUT]
    [, @cc_list = 'cc[;...n]' OUTPUT]
    [, @bcc_list = 'bcc[;...n]' OUTPUT]
    [, @date_received = 'date' OUTPUT]
    [, @unread = 'unread_value' OUTPUT]

實務應用範例

-- 每日備份完成通知
EXEC xp_sendmail
    @recipients = 'dba@company.com',
    @subject = 'SQL Server 備份完成報告',
    @message = '所有資料庫備份成功完成,詳見附件日誌。',
    @attachments = 'C:\Backup\Logs\backup_log.txt'

-- 異常作業警示 (搭配 Agent 作業)
EXEC xp_sendmail
    @recipients = 'oncall@company.com',
    @subject = 'SQL Server 作業失敗警示',
    @query = 'SELECT * FROM msdb.dbo.sysjobhistory WHERE run_status = 0 AND run_date = CONVERT(VARCHAR(8), GETDATE(), 112)',
    @attach_results = 'TRUE',
    @subject = '今日失敗作業清單'

前置需求

  • SQL Server 服務帳號需為網域帳號 (非 LocalSystem)
  • MAPI 郵件用戶端 (Outlook/Exchange) 正確設定於伺服器
  • SQL Mail 服務已啟動 (xp_startmail)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved