sqlserver2008自动发送邮件
这两天都在搞这个东西,从开始的一点不懂,到现在自己可以独立的完成这个功能!在这个过程中,CSDN的好多牛人都给了我很大的帮助,在此表示十二分的感谢!写这篇文章,一是为了巩固一下,二嘛我也很希望我写的这点小东西能帮助遇到同样问题的朋友们!当然这里有一部分是从网上的摘录的
DECLARE @account_name sysname, @profile_name sysname; SELECT @account_name = N'want_to_delete_Account' @profile_name = N'want_to_delete_Profile'; -- 从邮件配置文件中删除数据库邮件帐号 EXEC msdb.dbo.sysmail_delete_profileaccount_sp @profile_name = @profile_name, @account_name = @account_name; -- 删除数据库邮件帐号 EXEC msdb.dbo.sysmail_delete_account_sp @account_name = @account_name; -- 删除数据库邮件配置文件 EXEC msdb.dbo.sysmail_delete_profile_sp @profile_name = @profile_name;
完成了database mail的搭建。下面我们就要开始完善自动发送邮件的功能。
CREATE PROCEDURE [Services].[SendRegisteredEmail] ( @UserID int, @EmailAddress nvarchar(100) -- @mailitem_id int OUTPUT ) AS declare @userName nvarchar(30) declare @Login nvarchar(50) declare @password nvarchar(50) declare @regUserID int declare @titleName nvarchar(100) declare @titleResult nvarchar(100) declare @object nvarchar(600) declare @objectResult nvarchar(600) declare @Subject1 nvarchar(100) declare @Conclusion nvarchar(600) declare @Inscrible nvarchar(100) declare @result int --declare @time datetime declare @body1 nvarchar(max) begin select @userName=LastName from [Users].[User] where UserID=@UserID select @Subject1=Subject,@titleName=TitleName ,@object=Object,@Conclusion=Conclusion,@Inscrible=Inscribe from [Services].[EmailText] where EmailTypeID=1 select @titleResult=replace(@titleName,'<UserName>',@userName) select @Login=Login ,@password=Password from [Users].[RegisteredUser] where UserID=@UserID select @objectResult=replace(@object,'<LoginName>',@Login) select @objectResult=replace(@objectResult,'<LoginName>',@Login) set @body1=@titleResult+N'<br>'+@objectResult+N'<br>'+@Conclusion+N'<br>'+@Inscrible EXEC @result=msdb.dbo.sp_send_dbmail @profile_name='SurmountGroupProfile', @recipients=@EmailAddress, @subject= @Subject1, @body = @body1, @body_format = 'HTML'; return @result end
上面代码用了一个sql里的替换函数replace,该函数的用法是
declare @recordID int declare @userID int declare @email nvarchar(100) declare @typeID int declare @result int declare EmailCursor cursor for select RecordID,UserID,EmailAddress,EmailTextID from AutoSendEmail open EmailCursor fetch next from EmailCursor into @recordID,@userID,@email,@typeID While ( @@Fetch_Status=0 ) begin if( @typeID=1) begin exec @result=SendRegisteredEmail @userID,@email if(@result=0) begin delete from [Services].[AutoSendEmail] where RecordID=@recordID end end fetch next from EmailCursor into @recordID,@userID,@email,@typeID end close EmailCursor Deallocate EmailCursor
这里用游标遍历AutoSendEmail表,job设定为每分钟遍历一次,如果发送成功,就把该行记录给删除。否则保留在表中,下次遍历时,再次发送。 |