步骤:
1. 安装SMTP
2. 配置SMTP, 配置你要中转的邮件所用的邮件服务器,例如你的SMTP要中转Gmail的邮件,那么你就需要设置SMTP. 当然你可以配置自己POP3服务器,建立自己的域名,建立自己的邮件。
more info, see here:
http://fmuntean.wordpress.com/2008/10/26/how-to-configure-iis-smtp-server-to-forward-emails-using-a-gmail-account/
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:
http://blog.sqlauthority.com/2008/08/23/sql-server-2008-configure-database-mail-send-email-from-sql-database/
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 = 'MMM@hotmail.com', --你要给谁发邮件
@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被触发--->邮件发出