一、发送邮件配置
(1)配置工具里的 Surface Area Configure 工具来配置SQL允许发送邮件“Enable SQL Mail stored procedures" 和"Enable Database Mail stored procedure"
(2) sql Management studio --》management -->Database Mail-->右键”Configure Database Mail" 配置发送邮件 ,profle name 要记下来,一会用存储过程发的时候需要指定它。
二、发送邮件
这里用游标发送邮件,实用waiffor delay 在发了10封后休息1秒钟。
通过游标发送邮件,发了十封信户休息1秒钟
author:adandelin
createdate: 2008-01-19
*/
BEGIN TRY
Declare @MailAddress varchar(20),@Id int
DECLARE CMail CURSOR for
select top 2 usermail,UserId from usersmail
where issend=0 and updatedate <getdate()+1
open CMail
declare @Count int
set @count = 1
FETCH NEXT FROM CMail into @MailAddress,@id
while @@FETCH_STATUS =0
BEGIN
EXEC msdb.dbo.sp_send_dbmail --调用SQL2005的邮件发送的存储过程。
@profile_name = 'sohu', --就是在步骤2中的配置文件名。
--调用发送邮件的存储过程,登录帐号必须有msdb的datamail权限
@recipients = @Mailaddress,--用来接受邮件的地址
@subject = '诗词在线邮件',
@body = '<a href="http://www.52shici.cn" target="_blank" >诗词在线欢迎您!</a>' ,
@body_format ='HTML'
update usersmail
set isSend = '1'
where userid = @id
print @id
--如果发了10个了,那休息一秒钟
if @Count>9 and @count%10 = 0
begin
waitfor DELAY '00:01'
print 'delay 1 second'
end
SET @Count = @count+1
--下一列
FETCH NEXT FROM CMail
INTO @MailAddress, @id
END
--update usersmail set IsSend = 0
CLOSE CMail
DEALLOCATE CMail
END TRY
--捕捉异常
BEGIN CATCH
SELECT
ERROR_NUMBER() as ErrorNumber,
ERROR_MESSAGE() as ErrorMessage
END CATCH;
发送后可以
SELECT * FROM msdb.dbo.sysmail_allitems
来查看邮件发送是否成功。
如果想看详细的异常信息那么
SELECT * FROM msdb.dbo.sysmail_event_log
或者sql Management studio --》management -->Database Mail-->右键 View Database mail log
用10封测试的时候发送成功,后来发100个的时候有问题了。日志里:
xsi:schemaLocation="http://schemas.microsoft.com/databasemail/responses ResponseTypes.xsd" xmlns:responses="http://schemas.microsoft.com/databasemail/responses">
<Information>
<Failure Message="The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 2 (2008-01-19T23:12:21). Exception Message: Cannot send mails to mail server. (语法错误,无法识别命令。 服务器响应为: 5.7.0 Sohu sender blocked!). )" />
</Information>
<MailItemId Id="191" />
<SentStatus Status="3" />
<SentAccountId Id="0" />
<SentDate Date="2008-01-19T23:12:21" />
<CallingProcess Id="1892" />
</responses:SendMail>
估计是sohu有的邮件进行了设置不可以连续向一个邮箱发N个邮件吧。