步驟:
1. 安裝SMTP
2. 配置SMTP, 配置你要中轉的郵件所用的郵件服務器,例如你的SMTP要中轉Gmail的郵件,那麼你就需要設置SMTP. 當然你可以配置自己POP3服務器,建立自己的域名,建立自己的郵件。
more info, see here:
3. Enable Database Mail功能(SQL20008 or 2005)/Enable SQL Agent service via ruuning Services.MSC in cmd
4. 配置database Mail account and profile
more info:
or
http://www.db-staff.com/index.php/microsoft-sql-server/90-configure-database-mail
5. 在step4中,配置好"From" email address, 和 "Reply" email adress
6. 執行下列腳本(或者右鍵點擊Database Mail to sent a test):
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'JohnTest', --你在step4中建立的profile的名字
@recipients = '[email protected]', --你要給誰發郵件
@subject = 'aaa',
@body = 'just a test',
@body_format = 'HTML';
Example:
假設有一個需求,一個用戶在網站註冊了用戶信息後,收到網站註冊成功的郵件提示。
數據庫層:
建立表user; User(UserID, Name, Email, age, Sex,....)
建立表Emailqueue(EmailqueueID, UserID,To, Subject, body.....)
建立一個trigger on the talbe Emailqueue. Trigger tr_SendNotificationMail 觸發的操作爲inseration. Trigger中將包含類似的腳本:
.....
.....
declare @To string
declare @S string
declare @B string
.....
.....
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'JohnTest', --你在step4中建立的profile的名字
@recipients = @To --你要給誰發郵件
@subject =@S,
@body = @B,
@body_format = 'HTML';
建立存儲過程sp_insertUser; 這個存儲過程會向表Usere中插入數據,並且調用sp_insertEmail.
建立存儲過程sp_insertEmail; 這個存儲過程將向Emailqueue中插入數據,並被Sp_InsertUser調用。
流程:
用戶A註冊-->程序調用sp_insertuser-->用戶A被插入User表中;sp_InsertEmail被調用-->Email信息被插入Emailqueue表中
--->Trigger tr_SendNotificationMail被觸發--->郵件發出