Change SMTP server for all email profiles in SQL Server
It happens many times that we set SMTP server for database email profile in SQL Server instance and over the time we change email server and hence we need to change SMTP server in email profile also. We can change it manually from GUI of SSMS but what if you have multiple SQL Server instance and each SQL Server Instance is having multiple profiles? There is a chance we might miss profile while doing it manually so I would prefer to create script which can be run under each SQL Server Instance separately and update each profile under one SQL Server instance. After changing SMTP profile, we can’t keep it as it is before testing it properly so I have divided TSQL in two parts. First script will change SMTP server and second part of the script will shoot an email from each profile automatically so that we can assure our self that each profile working properly. I have used the same script for second part which I have had in “Check all database email profile in SQL Server by using sysmail_profile” article so do visit earlier article, if you haven’t read it.
Note: SMTP server given here are for demonstration purpose only, you have to use your own SMTP credentials there.
–Part 1: Update SMTP profile from smtp to smtp1
servername = ‘smtp1.google.com’
–Part 2: looping through profiles to shoot an email
SET @Total = (SELECT MAX(profile_id) FROM sysmail_profile)
SET @cnt = 1
SET @Server = @@SERVERNAME
WHILE(@cnt <= @Total) BEGIN SET @ProfileName = (SELECT name FROM sysmail_profile WHERE profile_id = @cnt) SET @Sub = @Server + ' - Profile: - ' + @ProfileName +' - ' + cast(@cnt as varchar) + ' of ' + cast(@Total as varchar) IF (@ProfileName is not null) BEGIN PRINT @ProfileName PRINT @Sub EXEC msdb.dbo.sp_send_dbmail @recipients = 'Test@gmail.com' , @subject = @Sub , @body = @Sub , @profile_name = @ProfileName , @body_format = 'HTML' ; END SET @cnt = @cnt + 1 END --Manually confirm "ServerName" is updated or not select * from sysmail_server[/sourcecode] If you like this article, do like “Extreme-Advice” page in Facebook.
Reference: Ritesh Shah
Note: Microsoft Books online is a default reference of all articles.