SQL Server 透過 SQL Mail 整合 Exchange/Outlook,提供一組擴展存儲程序實現郵件收發與自動化處理。本文系統整理核心程序參數與實戰用法。
-- 啟動
xp_startmail @user, @passWord -- 參數皆可選
-- 或企業管理員 → Support Services → SQL Mail 右鍵 → Start
-- 停止
xp_stopmail
-- 或企業管理員 → Stop
xp_sendmail
[@recipients =] 'recipients[;...n]' -- 必填,收件人以分號分隔
[,[@message =] 'message']
[,[@query =] 'query'] -- 查詢結果隨郵件發送
[,[@attachments =] 'attachments']
[,[@copy_recipients =] 'cc_list[;...n]']
[,[@blind_copy_recipients =] 'bcc_list[;...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'] -- 查詢使用資料庫,預設預設資料庫
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_list[;...n]' OUTPUT]
[,[@bcc_list =] 'bcc_list[;...n]' OUTPUT]
[,[@date_received =] 'date' OUTPUT]
-- 更多參數請參閱線上叢書
xp_sendmail 發送錯誤詳情給 DBA。@query 參數附上結果 → 定時寄送給業務主管。xp_readmail 掃描特定主旨郵件 → 解析內容 → 呼叫存儲程序處理訂單/核准單。sp_send_dbmail),架構更穩健、支援 SMTP、無 MAPI 相依。TRY...CATCH 記錄失敗日誌。掌握 xp_startmail/xp_stopmail/xp_sendmail/xp_readmail 四大核心程序,即可在 SQL Server 層面實現完整郵件收發自動化。新專案優先採用 Database Mail 以獲得更佳相容性與維護性。