Generate SQL Server Database Mail Configuration Scripts Using T-SQL
Setting up Database Mail in SQL Server is an important task, especially for sending alerts, job notifications, or custom messages from your SQL instance. While this can be configured through SQL Server Management Studio (SSMS), generating a repeatable T-SQL script allows you to automate and replicate your mail configuration across environments.
In this post, we'll walk through a T-SQL script that dynamically generates the configuration commands for existing Database Mail profiles, accounts, and server settings. This script pulls metadata from msdb and creates a reusable script block for recreating the configuration elsewhere.
Overview of the Script
The script does the following:
-
Enables required configuration settings (
Database Mail XPs). -
Generates script blocks to:
-
Create mail profiles if they don’t exist.
-
Create mail accounts with their respective settings.
-
Associate mail accounts with profiles.
-
-
Optionally includes commented-out commands to drop these configurations.
This is useful for backup purposes or for migrating Database Mail configurations to another server.
T-SQL Script for Mail Configuration Generation
Here’s the simplified logic behind the actual T-SQL that builds the configuration script:
Why Use This Script?
-
Documentation: Quickly generate a readable backup of your email configuration.
-
Migration: Move Database Mail settings to another SQL Server instance with minimal effort.
-
Automation: Integrate this logic into CI/CD pipelines or setup scripts.
🔐 Note: The script replaces real passwords with
'NotTheRealPassword'. Always handle credentials securely when adapting this for production use.