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

SQL Server 設定 Database Mail 發送郵件:無 Exchange 環境下的完整配置指南

     編輯:關於SqlServer

適用環境

  • Windows 2000 Server / Windows Server 2003+
  • SQL Server 2000 SP3+ / 2005+
  • Microsoft Outlook (Office 2000+)
  • 無 Exchange Server,使用公共 SMTP/POP3 (如 163, Gmail, 企業郵箱)

核心原理

SQL Server Agent 服務啟動帳戶的 Windows 設定檔中配置 Outlook 郵件設定檔,SQL Mail 透過 MAPI 呼叫 Outlook 發信。

步驟 1:Outlook 郵件支援模式切換

  1. Outlook → 「工具」→ 「選項」→ 「郵件服務」標籤
  2. 點選「重新配置郵件支援」
  3. 選擇 「企業或工作組」 模式
  4. 重新啟動 Outlook

步驟 2:建立 Internet 郵件設定檔

  1. Outlook → 「工具」→ 「服務」→ 「新增」
  2. 選擇 「Internet 電子郵件」
  3. 填寫帳戶資訊:
    • 電子郵件地址:test@163.com
    • SMTP 伺服器:smtp.163.com
    • POP3 伺服器:pop.163.com
    • 帳戶/密碼:依郵箱提供商要求
  4. 測試收發確認設定檔正常

步驟 3:SQL Server Agent 服務帳戶關鍵設定

⚠ 核心要求:SQL Server Agent 服務啟動帳戶 = 登入 Windows 並配置 Outlook 的帳戶

  1. 服務管理器 → SQL Server Agent → 右鍵「屬性」→ 「登入」標籤
  2. 設定為具備 Outlook 設定檔的網域/本地帳戶
  3. 重新啟動 SQL Server Agent 服務 (必須,否則偵測不到新設定檔)

步驟 4:企業管理員啟用 SQL Mail

  1. 企業管理員 → 伺服器群組 → 「支援服務」→ 「SQL Mail」右鍵
  2. 下拉選單出現 「Microsoft Outlook Internet Settings」
  3. 選中 → 「測試」→ 彈出成功對話框即配置完成

步驟 5:測試發送

-- 查詢分析器執行
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 服務帳戶有檔案讀取權限

現代替代方案:Database Mail (SQL Server 2005+)

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,但規劃遷移路徑。

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