Create a Database Mail Account in SQL Server (T-SQL)

If you’re setting up Database Mail to send emails in SQL Server, you will need to have at least one Database Mail account.

You can create Database Mail accounts with T-SQL by executing the sysmail_add_account_sp stored procedure in the msdb database.

The Database Mail account is the account that sends the email. For example, if you have an automated email that is sent whenever a SQL Server Agent job fails, this is the account that sends that email.

You can also specify things such as a separate “reply-to” email, a display name, etc.

You can have multiple accounts for various tasks if required. Simply execute sysmail_add_account_sp whenever you need to create a new account.

Example

Here’s an example of creating a Database Mail account.

EXECUTE msdb.dbo.sysmail_add_account_sp  
    @account_name = 'DB Admin',  
    @description = 'Mail account for admin emails.',  
    @email_address = '[email protected]',  
    @replyto_address = '[email protected]',  
    @display_name = 'DB Automated Mailer',  
    @mailserver_name = 'smtp.example.com',
    @port = 25;

In this example I specify a display name of “DB Automated Mailer”. This is a user-friendly name that conveys to the recipient who sent the email. You could use “SQL Server Agent” or similar, depending on your setup.

The Syntax

The above example doesn’t include all available options.

The official syntax goes like this:

sysmail_add_account_sp  [ @account_name = ] 'account_name',  
    [ @email_address = ] 'email_address' ,  
    [ [ @display_name = ] 'display_name' , ]  
    [ [ @replyto_address = ] 'replyto_address' , ]  
    [ [ @description = ] 'description' , ]  
    [ @mailserver_name = ] 'server_name'   
    [ , [ @mailserver_type = ] 'server_type' ]  
    [ , [ @port = ] port_number ]  
    [ , [ @username = ] 'username' ]  
    [ , [ @password = ] 'password' ]  
    [ , [ @use_default_credentials = ] use_default_credentials ]  
    [ , [ @enable_ssl = ] enable_ssl ]  
    [ , [ @account_id = ] account_id OUTPUT ]

See the Microsoft documentation for a detailed explanation of each argument. You can use whichever arguments suit your situation.

You can also use the sysmail_update_account_sp stored procedure to update an existing Database Mail account.

Configuring Database Mail

Creating a Database Mail account is just one of several things you need to do before you can send email with that account.

Once you’ve created the account, you’ll need to add it to a profile (which means you’ll also need to create a profile if you don’t already have one). You’ll also need to grant a user in the msdb database access to the profile.

See How to Send Email in SQL Server for a complete example of configuring Database Mail, then sending an email.