这篇文章主要介绍如何使用SQL数据库发mail,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
一、先启动邮件服务
SQL SCRIPTS
exec master..sp_configure 'show advanced options',1
go
reconfigure
go
exec master..sp_configure 'Database mail XPs',1
go
reconfigure
go
二、创建发邮件时所需要的account
exec msdb..sysmail_add_account_sp
@account_name = 'OPSDBA',--邮件账户(account)名
@description = 'Mail account for administrative e-mail.',
@email_address = 'monitor.dataops@mail.COM',--发件人邮件地址
@display_name = 'dataops_monitor',--发件人显示名称
@mailserver_name = 'smtp邮件服务器地址',--smtp邮件服务器地址
@port = 25
官方sample
https://msdn.microsoft.com/zh-cn/library/ms182804.aspx
验证
EXECUTE msdb.dbo.sysmail_help_account_sp ;
三、创建profile
--创建profile
exec msdb..sysmail_add_profile_sp
@profile_name = 'monitor',--profile名称
@description='监控邮件配置文件'
验证
EXECUTE msdb.dbo.sysmail_help_profile_sp ;
四、关联account和profile
exec msdb..sysmail_add_profileaccount_sp
@profile_name = 'monitor',--profile名称
@account_name = 'OPSDBA',--account名称
@sequence_number = 1--account在profile中顺序
验证
EXECUTE msdb.dbo.sysmail_help_profileaccount_sp
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@principal_name = 'dba_monitor',
@profile_name = 'monitor',
@is_default = 1 ;
五、发送邮件
exec msdb..sp_send_dbmail
@profile_name = 'monitor',--profile名称
@recipients = 'rr@123.com',--收件人邮箱(有多个邮箱用分号分开)
@subject = 'SQL Server 2005 Mail 测试',--邮件标题
@body = 'Hello Mail!测试'--邮件内容
-=====================================
declare @sql varchar(8000);
set @sql='SELECT top 20 a.[databse_name]
,a.[table_name]
,a.[row_count]
,a.[reserved_space]
,a.[used_space] [used_space_0408]
,b.[used_space] [used_space_0401]
,a.[index_space]
,a.[unused_space]
,a.[record_time]
,convert(int,replace(a.[used_space],'+''''+'KB'+''''+','+''''+''''+'))-convert(int,replace(b.[used_space],'+''''+'KB'+''''+','+''''+''''+')) inc_space_KB
FROM [DBCenter].[dbo].[viewTableSpace] a join [DBCenter].[dbo].[viewTableSpace] b
on a.databse_name=b.databse_name and a.table_name=b.table_name and convert(varchar(10),a.[record_time],120) =convert(varchar(10),dateadd(day,0,getdate()),120)
and convert(varchar(10),b.[record_time],120)=convert(varchar(10),dateadd(day,-7,getdate()),120)
order by inc_space_KB desc'
--print @sql
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'monitor',
@recipients = 'yuqing.zhu@datayes.com',
@query = @sql ,
@subject = 'weekly table increase top 20',
@attach_query_result_as_file = 1 ;
以上是“如何使用SQL数据库发mail”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!