現代 SQL Server (2005+) 推薦使用 Database Mail 替代舊版 xp_sendmail/SQLMail(依賴 MAPI/Outlook/Exchange)。Database Mail 基於 SMTP,無需 Outlook/Exchange,支援 SSL/TLS、多設定檔、異步佇列、重試機制,配置更簡單、穩定。
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'Database Mail XPs', 1; RECONFIGURE;
EXEC msdb.dbo.sysmail_add_account_sp
@account_name = 'MySmtpAccount',
@email_address = 'sender@company.com',
@display_name = 'SQL Server Auto Mailer',
@replyto_address = 'noreply@company.com',
@description = 'SMTP account for DB alerts',
@mailserver_name = 'smtp.company.com', -- SMTP 伺服器
@port = 587, -- 587(TLS) / 465(SSL) / 25(無加密)
@username = 'sender@company.com',
@password = 'YourAuthCodeOrPassword',
@enable_ssl = 1; -- 1=SSL/TLS, 0=無加密
EXEC msdb.dbo.sysmail_add_profile_sp
@profile_name = 'DefaultProfile',
@description = 'Default mail profile for all DBs';
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'DefaultProfile',
@account_name = 'MySmtpAccount',
@sequence_number = 1; -- 優先級,多帳號時生效
EXEC msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'DefaultProfile',
@principal_name = 'public', -- 或特定用戶/角色
@is_default = 1; -- 設為預設
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DefaultProfile',
@recipients = 'admin@company.com',
@subject = 'Test from SQL Server',
@body = 'Database Mail 配置成功!',
@body_format = 'HTML'; -- 或 'TEXT'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DefaultProfile',
@recipients = 'dba@company.com',
@subject = 'Daily Backup Report',
@body = '附件為今日備份狀態',
@query = 'SELECT Database_Name, Backup_Start_Date, Backup_Finish_Date, Backup_Size_MB FROM msdb.dbo.Backup_History WHERE Backup_Start_Date >= DATEADD(DAY, -1, GETDATE())',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'BackupReport.csv',
@query_result_separator = ',',
@query_result_header = 1;
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DefaultProfile',
@recipients = 'admin@company.com',
@subject = 'Error Log',
@body = '請查收錯誤日志',
@file_attachments = 'C:\Logs\ERRORLOG';
| 現象 | 排查方向 |
|---|---|
| 郵件卡在佇列 (sent_status = unsent) | 查看 msdb.dbo.sysmail_event_log 錯誤碼;檢查 SMTP 連通性、防火牆、端口、SSL 設定 |
| 認證失敗 | 確認帳號/密碼/授權碼;Gmail/Outlook 需開啟「低安全性應用」或生成應用專用密碼 |
| 發件人被拒 | SMTP 伺服器要求發件人與認證帳號一致;設置 @email_address = @username |
| 大附件失敗 | 調整 @max_attach_size (預設 1MB) 或 SMTP 伺服器限制 |
舊代碼 EXEC master..xp_sendmail ... 需逐一改為 sp_send_dbmail,參數映射:
@recipients → @recipients@subject → @subject@message → @body@file_attachments/@queryDatabase Mail 是 SQL Server 發送郵件的標準、現代、無依賴方案。棄用 SQLMail/MAPI/Outlook,擁抱 SMTP + Database Mail,獲得更好的可靠性、安全性與可維護性。