本文實為 SQL Server 的 Database Mail 功能設定(非 MySQL),常用於資料庫層直接發送郵件通知。
方法一:SSMS 圖形介面
AppMailProfile)msdb 相關物件方法二:T-SQL 指令
-- 啟用 Database Mail
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 = 'SMTP_Account',
@email_address = 'noreply@company.com',
@display_name = '系統自動通知',
@mailserver_name = 'smtp.company.com',
@port = 587,
@username = 'smtp_user',
@password = 'smtp_password',
@enable_ssl = 1;
-- 建立設定檔
EXEC msdb.dbo.sysmail_add_profile_sp
@profile_name = 'AppMailProfile',
@description = '應用程式郵件設定檔';
-- 關聯帳號與設定檔
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'AppMailProfile',
@account_name = 'SMTP_Account',
@sequence_number = 1;
-- 設為公開預設
EXEC msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'AppMailProfile',
@principal_name = 'public',
@is_default = 1;
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AppMailProfile',
@recipients = 'test@company.com',
@subject = 'Database Mail 測試',
@body = '這是一封測試郵件,發送時間:' + CONVERT(VARCHAR, GETDATE(), 120),
@body_format = 'HTML';
CREATE PROCEDURE usp_NotifyUserRegistration
@Email NVARCHAR(256),
@UserName NVARCHAR(100),
@TempPassword NVARCHAR(50)
AS
BEGIN
DECLARE @Body NVARCHAR(MAX) =
N'歡迎註冊 ' + @UserName + N'
' +
N'您的暫時密碼:' + @TempPassword + N'
' +
N'請登入後立即修改密碼。
';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AppMailProfile',
@recipients = @Email,
@subject = '帳號註冊成功通知',
@body = @Body,
@body_format = 'HTML';
END;
DatabaseMailUserRole 角色EXEC sp_addrolemember 'DatabaseMailUserRole', 'AppUser';sp_send_dbmail:GRANT EXECUTE ON msdb.dbo.sp_send_dbmail TO AppUser;| 檢視 | 用途 |
|---|---|
msdb.dbo.sysmail_mailitems | 郵件隊列狀態 |
msdb.dbo.sysmail_log | 發送記錄與錯誤 |
msdb.dbo.sysmail_event_log | Database Mail 內部事件 |
-- 查詢失敗郵件
SELECT * FROM msdb.dbo.sysmail_mailitems
WHERE sent_status = 'failed'
ORDER BY send_request_date DESC;
-- 查詢錯誤詳情
SELECT * FROM msdb.dbo.sysmail_log
WHERE event_type = 'error'
ORDER BY log_date DESC;
SELECT is_broker_enabled FROM sys.databases WHERE name='msdb';Database Mail 設定檔 → 系統參數 → 最大執行緒數@file_attachments 參數,大檔案建議上傳雲端給連結@body_format = 'HTML',支援豐富排版Database Mail 將郵件發送能力內建於資料庫層,減少應用層依賴,提升系統內聚性與可靠度。