SQL 发送Email

来源:互联网 发布:2016淘宝开店新规定 编辑:程序博客网 时间:2024/06/07 02:04

--1. 启用  邮件功能。
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

--2. 添加邮件帐户(account) 
exec msdb..sysmail_add_account_sp
        @account_name            = 'ScheduleBillingEmail'           -- 邮件帐户名称(SQL Server 使用)
       ,@email_address           = 'test@163.com'                   -- 发件人邮件地址
       ,@display_name            = 'test@163.com'                   -- 发件人姓名(回复地址)
       ,@replyto_address         = null
       ,@description             = null
       ,@mailserver_name         = 'smtp.163.com'                  -- 邮件服务器地址smtp.gmail.com
       ,@mailserver_type         = 'SMTP'                              -- 邮件协议(SQL 2005 只支持 SMTP)
       ,@port                    = 25                                        -- 邮件服务器端口
       ,@username                = 'test@163.com'                   -- 用户名
       ,@password                = 'test'                                 -- 密码
       ,@use_default_credentials = 0
       ,@enable_ssl              = 0
       ,@account_id              = null
 
 
 --3. 添加 profile
exec msdb..sysmail_add_profile_sp @profile_name = 'dba_ScheduleBilling'           -- profile 名称
                                 ,@description  = 'dba mail profile'                               -- profile 描述
                                 ,@profile_id   = null

--4. 映射 account 和 profile(授予任意用户使用数据库邮件配置文件的权限)
exec msdb..sysmail_add_profileaccount_sp  @profile_name    = 'dba_ScheduleBilling'      -- profile 名称
                                         ,@account_name    = 'ScheduleBillingEmail'                   -- account 名称
                                         ,@sequence_number = 1                                          -- account 在 profile 中顺序
                                        
                                        
--5. 利用 SQL Server 2005 Database Mail 功能发送邮件。                              

exec msdb..sp_send_dbmail @profile_name =  'dba_ScheduleBilling'                             -- profile 名称
                         ,@recipients   =  'test@163.com'          -- 收件人邮箱
                         ,@subject      =  'SQL Server 2008 Mail Test' -- 邮件标题
                         ,@body         =  'Hello Mail!'               -- 邮件内容
                         ,@body_format  =  'TEXT'                      -- 邮件格式