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

SQL Server SQLMail 郵件收發與自動化處理完整指令參考

     編輯:關於SqlServer

前言

SQL Server 透過 SQLMail 擴充預存程序,可整合 Microsoft Exchange 或 Outlook 實現資料庫層級的郵件收發與事件驅動自動化。本文彙整核心指令語法與參數說明。

一、 服務控制

操作T-SQL 指令GUI 操作
啟動xp_startmail [@user], [@password](參數可選)企業管理員 → 支援服務 → SQLMail 右鍵 → 啟動
停止xp_stopmail同處 → 停止

二、 寄送郵件:xp_sendmail

xp_sendmail
  [@recipients =] 'recipients[;...]'
, [@message =] 'message'
, [@query =] 'query'
, [@attachments =] 'attachments'
, [@copy_recipients =] 'cc_list'
, [@blind_copy_recipients =] 'bcc_list'
, [@subject =] 'subject'
, [@type =] 'type'
, [@attach_results =] 'TRUE|FALSE'
, [@no_output =] 'TRUE|FALSE'
, [@no_header =] 'TRUE|FALSE'
, [@width =] width
, [@separator =] 'separator'
, [@echo_error =] 'TRUE|FALSE'
, [@set_user =] 'user'
, [@dbuse =] 'database'

關鍵參數說明

  • @recipients:必要,多位收件人以分號分隔。
  • @query:任意有效查詢,結果可附件寄出(觸發器 inserted/deleted 表除外)。
  • @attach_results:TRUE 時將查詢結果以附件形式附加。
  • @no_header:TRUE 時不包含欄位標題列。
  • @set_user:查詢執行內容用戶,預設 Guest。
  • @dbuse:查詢使用的資料庫,預設為目前資料庫。

三、 讀取收件箱:xp_readmail

xp_readmail
  [@msg_id =] message_number
, [@type =] 'type' OUTPUT
, [@peek =] 'TRUE|FALSE'          -- TRUE=不標記已讀
, [@suppress_attach =] 'TRUE|FALSE'
, [@originator =] 'sender' OUTPUT
, [@subject =] 'subject' OUTPUT
, [@message =] 'message' OUTPUT
, [@recipients =] 'recipients' OUTPUT
, [@cc_list =] 'cc_list' OUTPUT
, [@bcc_list =] 'bcc_list' OUTPUT
, [@date_received =] 'date' OUTPUT
, [@unread =] 'unread_flag' OUTPUT
, [@attachments =] 'attachments' OUTPUT
, [@skip_bytes =] bytes OUTPUT
, [@msg_length =] length OUTPUT
, [@originator_address =] 'address' OUTPUT

四、 典型自動化場景

  1. 排程報表寄送: Agent 作業每日執行 xp_sendmail @query='SELECT ...', @attach_results='TRUE'。
  2. 異常警報: 觸發器/作業偵測錯誤 → xp_sendmail @recipients='dba@corp.com', @subject='Alert', @message=@errmsg。
  3. 郵件觸發業務流程: 定期 xp_readmail @peek='TRUE' 掃描特定主題/寄件者 → 解析內容 → 執行對應預存程序 → xp_readmail @msg_id=..., @peek='FALSE' 標記已處理。

五、 遷移建議

SQL Server 2005+ 已淘汰 SQLMail,改用 Database Mail(sp_send_dbmail),架構更穩定、不依賴 MAPI/Outlook、支援非同步佇列與重試機制。新專案請直接採用 Database Mail;現有 SQLMail 系統規劃升級路徑。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved