Batch modify the dbmail configuration of recommendation for all servers

  • 2020-06-23 02:19:42
  • OfStack

Recently, I encountered such a case that the Database Mail of all SQL Server needs to be modified. The original SMTP was 10. xxx.xxx.xxx, but now it needs to be modified to 192.168. xxx.xxx.

If the UI interface of SSMS client is used to modify, so many servers will be modified one by one, which is time-consuming and tedious. Only use scripts, once you have written one script, then use Multiple Server Query Execution (it is highly recommended to use this to manage and maintain the database), execute the script once, all done. The rest of the time you can drink tea and learn something new!


DECLARE @EmailAccount sysname;
DECLARE @SmtpServer sysname;
DECLARE @EmailAddress NVARCHAR(120);
DECLARE @EmailSuffix NVARCHAR(32);
DECLARE @NewEamilAddress NVARCHAR(120);
--DECLARE @ActualEmailSuffix NVARCHAR(32)='xxxx.com'; SQL Server 2005 This feature is not supported and will be reported Cannot assign a default value to a local variable.
DECLARE @ActualEmailSuffix NVARCHAR(32);
DECLARE @ActualSmtpServer sysname;
SET @ActualEmailSuffix='xxx.com';
SET @ActualSmtpServer='192.168.xxx.xxx';
DECLARE EmailAccount_Cursor CURSOR FAST_FORWARD
FOR
SELECT sa.[name]    
   ,ss.[servername] 
   ,sa.email_address
 FROM [msdb].[dbo].[sysmail_server] ss 
 INNER JOIN [msdb].[dbo].[sysmail_account] sa
 ON ss.[account_id]=sa.[account_id];
OPEN EmailAccount_Cursor;
FETCH NEXT FROM EmailAccount_Cursor INTO @EmailAccount, @SmtpServer,@EmailAddress;
WHILE @@FETCH_STATUS = 0
BEGIN
  IF LTRIM(RTRIM(@SmtpServer))!=@ActualSmtpServer
  BEGIN
    EXECUTE msdb.dbo.sysmail_update_account_sp
       @account_name = @EmailAccount
      ,@mailserver_name=@ActualSmtpServer;
    PRINT @SmtpServer;
    PRINT @EmailAccount;
  END;
  SET @EmailSuffix=SUBSTRING(@EmailAddress,CHARINDEX('@',@EmailAddress)+1, LEN(@EmailAddress) -CHARINDEX('@',@EmailAddress))
  IF @EmailSuffix!=@ActualEmailSuffix
  BEGIN
    SET @NewEamilAddress= REPLACE(@EmailAddress,@EmailSuffix,@ActualEmailSuffix);
    EXECUTE msdb.dbo.sysmail_update_account_sp
       @account_name = @EmailAccount
      ,@email_address=@NewEamilAddress
      ,@mailserver_name=@SmtpServer;
    PRINT @EmailAccount;
    PRINT @NewEamilAddress;
  END;
  FETCH NEXT FROM EmailAccount_Cursor INTO @EmailAccount, @SmtpServer,@EmailAddress;
END
CLOSE EmailAccount_Cursor;
DEALLOCATE EmailAccount_Cursor;


Related articles: