SQL Server Agent 服務啟動帳戶的 Windows 設定檔中配置 Outlook 郵件設定檔,SQL Mail 透過 MAPI 呼叫 Outlook 發信。
⚠ 核心要求:SQL Server Agent 服務啟動帳戶 = 登入 Windows 並配置 Outlook 的帳戶
-- 查詢分析器執行
EXEC master..xp_sendmail
@recipients = 'test@163.com',
@subject = 'SQL Server Mail Test',
@message = 'Hello, World!';
| 現象 | 原因 | 解決 |
|---|---|---|
| 下拉無 Outlook 設定檔 | Agent 服務帳戶 ≠ 配置 Outlook 的帳戶 | 統一服務帳戶並重啟 Agent | 測試失敗「MAPI 錯誤」 | Outlook 未設為預設郵件用戶端 / 設定檔損壞 | 重建設定檔、設為預設 |
| 發送無回應/卡住 | Outlook 安全性提示「程式嘗試存取通訊錄」 | Outlook 信任中心 → 程式設計存取 → 允許 |
| 附件發送失敗 | 路徑權限 / 檔案不存在 | 確保 Agent 服務帳戶有檔案讀取權限 |
SQL Mail 已淘汰,Database Mail 為原生 SMTP 實作,無需 Outlook/MAPI:
-- 建立帳戶
EXEC msdb.dbo.sysmail_add_account_sp
@account_name = 'SMTP_Account',
@email_address = 'sqlagent@company.com',
@mailserver_name = 'smtp.company.com',
@port = 25,
@username = 'smtp_user',
@password = 'password';
-- 建立設定檔並關聯帳戶
EXEC msdb.dbo.sysmail_add_profile_sp @profile_name = 'SQL_Alerts';
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'SQL_Alerts', @account_name = 'SMTP_Account', @sequence_number = 1;
-- 發送測試
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL_Alerts',
@recipients = 'dba@company.com',
@subject = 'Database Mail Test',
@body = 'Native SMTP, no Outlook required!';
新專案請直接使用 Database Mail。舊系統維護期內可續用 SQL Mail,但規劃遷移路徑。