Scripting setup of database mail

筅森魡賤 提交于 2019-12-18 04:39:12

问题


I've used the SQL Server 2008 GUI to set up database mail profiles & accounts on my test server, and I'd now like to duplicate those to our production database.

Is there a way to generate a script to do this?


回答1:


AFAIK, there isn't a way to necessarily script this from SSMS but you can create a transportable script in TSQL once and reuse it on all the servers. Here is a good example to get you started with this:

USE [master]
GO
sp_configure 'show advanced options',1
GO
RECONFIGURE WITH OVERRIDE
GO
sp_configure 'Database Mail XPs',1
GO
RECONFIGURE 
GO
-- Create a New Mail Profile for Notifications
EXECUTE msdb.dbo.sysmail_add_profile_sp
       @profile_name = 'DBA_Notifications',
       @description = 'Profile for sending Automated DBA Notifications'
GO
-- Set the New Profile as the Default
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'DBA_Notifications',
    @principal_name = 'public',
    @is_default = 1 ;
GO
-- Create an Account for the Notifications
EXECUTE msdb.dbo.sysmail_add_account_sp
    @account_name = 'SQLMonitor',
    @description = 'Account for Automated DBA Notifications',
    @email_address = 'email@domain.com',  -- Change This
    @display_name = 'SQL Monitor',
    @mailserver_name = 'smtp.domain.com'  -- Change This
GO
-- Add the Account to the Profile
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'DBA_Notifications',
    @account_name = 'SQLMonitor',
    @sequence_number = 1
GO

The other option would be to leverage SMO, either through .NET or powershell to generate the scripts. The SMO reference for this would be:

SqlMail Class

UPDATE:

Here is how easy it turned out to be to script this with Powershell and SMO:

[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo");

#Set the server to script from
$ServerName = "ServerName";

#Get a server object which corresponds to the default instance
$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server $ServerName

#Script Database Mail configuration from the server
$srv.Mail.Script();


来源:https://stackoverflow.com/questions/3521456/scripting-setup-of-database-mail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!