数据库邮件

来源:互联网 发布:全球购淘宝店直播条件 编辑:程序博客网 时间:2024/05/22 00:10

在SQL Server中配置好Database Mail之后,可以使用存储过程 msdb.dbo.sp_send_dbmail 给特定的User发送mail,或在第一时间通知DBA数据库执行的异常情况,是一个非常不错的功能。 

一,配置数据库邮件

1,在SSMS的Management中,点击Database Mail打开Database Mail Configuration Wizard

2,创建Profile

在发送database mail的时候,需要指定数据库邮件的Profile,Profile一个配置文档,包含SMTP Server地址,SMTP Server身份验证等的配置文档。

点击Add,创建SMTP Account。

3,增加SMTP Account,需要配置Database mail的发送地址,SMTP Server URL和 SMTP Server Authentication

4,设置默认的Profile,

如果设置了默认的Profile,执行msdb.dbo.sp_send_dbmail 时不需要@profile_name显式指定Profile name。

 5,发送测试mail

Database Mail 自带有"Send Test E-Mail"和“View Database Mail Log”的功能,用来查看Database mail的发送情况。

 二,使用TSQL语句发送mail

1,使用 msdb.dbo.sp_send_dbmail 发送mail,由于设置了default profile,所以不需要显示使用@Profile_Name来指定Profile。

EXEC msdb.dbo.sp_send_dbmail    @recipients='xxx@domainname.com'    ,@subject='Test email subject'    ,@body='test email body'    --,@profile_name='default'

使用msdb.dbo.sp_send_dbmail也能发送HTML格式的mail,需要在参数@body_format指定格式。
@body_format= ] 'body_format'

默认值是Text,表示发送的是邮件正文是text格式;HTML格式,可以使用HTML 标签

2,发送text格式的邮件

复制代码
EXEC msdb.dbo.sp_send_dbmail    @recipients='xxx@domainname.com'    ,@subject='Test email subject'    ,@body='test email body'    --,@profile_name='default_ProfileName'    --,@body_format='text'
复制代码

@Body_Format 参数的默认值是Text

3,发送Html格式的mail

复制代码
declare @htmlbody varchar(max)set @htmlbody='<table><tr>    <td>first row</td></tr><tr>    <td>second row</td></tr></table>'EXEC msdb.dbo.sp_send_dbmail    @recipients='xxx@domainname.com'    ,@subject='Test email subject'    ,@body=@htmlbody    --,@profile_name='default_ProfileName'    ,@body_format='Html'
复制代码

4,将查询结果作为mail的body

存储过程 msdb.dbo.sp_send_dbmail 可以执行一个select 查询子句,并将查询结果作为一个附件发送出去。

复制代码
EXEC msdb.dbo.sp_send_dbmail    @recipients='xxx@domainname.com'    ,@subject='Test email subject'    --,@profile_name='default_ProfileName'    --,@body_format='text'    ,@query='select * from db_study.dbo.test'    ,@attach_query_result_as_file = 1
0 0
原创粉丝点击