You are on page 1of 24

DASH_SQL Database Mail_TA423_Installation and

Configuration Guide_v0.1

TA423
Installation and Configuration Guide
For Database Mail in MS SQL Server 2008 R2

DASH Program
Release 1

Prepared By : Joan Z. Demafelis

Date : 03/14/2013

Version : 0.1

Accenture Proprietary and Confidential Page 1 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Table of Contents

CONFIGURING AND USING DATABASE MAIL IN SQL SERVER 2008..............................................................2


Configure Database Mail - Database Mail Configuration Wizard.............................................................2
Verify SQL Server Agent is Running..............................................................................................2
Verify Service Broker is Enabled for the msdb Database.....................................................................3
Enable Database Mail..........................................................................................................................4
Create E-Mail Profile and SMTP Account.............................................................................................5
Sending a Test E-mail.........................................................................................................................12
Configuring Security in Database Mail...................................................................................................14
The DatabaseMailUserRole Role.......................................................................................................14
Create a User for Database Mail........................................................................................................14
Send E-Mail from Database Mail...........................................................................................................15
Send a Simple Text E-Mail Message...................................................................................................16
Send an E-Mail Message with File Attachment..................................................................................16
Configure Email Notification for SQL Server Agent............................................................................17
Managing Database Mail.......................................................................................................................18
How to Start and Stop Database Mail................................................................................................18
Archive Database Mail Messages and Event Logs..............................................................................19
Create a SQL Server Agent Job...................................................................................................20
Create a Step to Archive the Database Mail Messages............................................................20
Create a Step to Archive the Database Mail Attachments........................................................21
Create a Step to Archive the Database Mail Log.......................................................................22
Create a Step to Remove the Archived Rows from Database Mail.........................................23
Create a Step to Remove the Archived Items from Database Mail Event Log.......................23
Schedule the Job to Run at the Start of Each Month.................................................................24

Accenture Proprietary and Confidential Page 2 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

CONFIGURING AND USING DATABASE MAIL IN SQL SERVER 2008

Configure Database Mail - Database Mail Configuration Wizard

Before using Database Mail, several configuration tasks need to be carried out. This section
describes the steps necessary to successfully configure Database Mail which includes verifying that the
SQL Server Agent is running, verifying that the Service Broker is enabled for the msdb database, enabling
the Database Mail feature, and finally, creating an e-mail Profile and SMTP mail account using the
Database Mail Configuration Wizard.

Verify SQL Server Agent is Running

Messages in Database Mail are sent by the SQL Server Agent. If the Agent is not running, the
messages will be accumulated in the msdb database and sent when the Agent service gets started again

Use the master..xp_servicecontrol system stored procedure to check the status of the SQL


Server Agent process. If the Agent is stopped, you will want to start it in order to send messages through
Database Mail.

USE master
Go

EXEC xp_servicecontrol N'QueryState', N'SQLServerAGENT';


Go

If SQL Server Agent is stopped, perform the following procedure:

1. Go to Start > All Programs > Microsoft SQL Server 2008 R2 > Configuration Tools and
select SQL Server Configuration Manager.
2. Under SQL Server Configuration Manager (Local), select SQL Server Services.
3. On the right panel, right-click SQL Server Agent (MSSQLSERVER) and click Start.

Accenture Proprietary and Confidential Page 3 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Verify Service Broker is Enabled for the msdb Database

Database Mail relies on Service Broker for queuing e-mail messages. If Database Mail is stopped
or if Service Broker message delivery is not activated in the msdb database, Database Mail queues
messages in the database but cannot deliver the messages. In this case, the Service Broker messages
remain in the Service Broker Mail queue. Service Broker does not activate the external program, so there
are no log entries in sysmail_event_log and no updates to the item status in sysmail_allitems and the
related views.

Verify that Service Broker is enabled for the msdb database by running the following query.

USE master
Go

SELECT is_broker_enabled
FROM sys.databases
WHERE database_id = DB_ID(N'msdb');
Go

is_broker_enabled will be 1 if Service Broker is enabled for the given database (msdb), otherwise it will
be 0.

If the Service Broker is disabled (is_broker_enabled = 0), run the following T-SQL to enable Service
Broker for the msdb database:

USE master
Go

ALTER DATABASE msdb SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;


Go

Accenture Proprietary and Confidential Page 4 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Enable Database Mail

Database Mail relies on a number of internal stored procedures. To reduce the surface area, these
stored procedures are disabled on new installations of SQL Server which makes Database Mail not active
by default. Users must explicitly enable these Database Mail stored procedures by using either one of the
the following three methods.

1. sp_configure Stored Procedure

To enable Database Mail using the sp_configure stored procedure, run the following.

USE master
Go

EXEC sp_configure 'show advanced options', 1


Go

Expected result: Configuration option 'show advanced options'


changed from 0 to 1. Run the RECONFIGURE statement to install.

RECONFIGURE
Go

Command(s) completed successfully.

EXEC sp_configure 'Database Mail XPs', 1


Go

Expected result: Configuration option 'Database Mail XPs' changed


from 0 to 1. Run the RECONFIGURE statement to install.

RECONFIGURE
Go

Command(s) completed successfully.

EXEC sp_configure 'show advanced options', 0


Go

Expected result: Configuration option 'show advanced options'


changed from 1 to 0. Run the RECONFIGURE statement to install.

RECONFIGURE
Go

Accenture Proprietary and Confidential Page 5 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create E-Mail Profile and SMTP Account

After enabling the Database Mail feature, the next step is to use the Database Mail Configuration
Wizard to create an e-mail Profile and an SMTP Account through which to send emails.

1. To start the Database Mail Configuration Wizard, in Object Explorer, expand the
Management folder in SQL Server Management Studio, right-click Database Mail, and
select Configure Database Mail.

2. This will bring up the Database Mail Configuration Wizard welcome screen. Click Next to continue

Accenture Proprietary and Confidential Page 6 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

3. On the Select Configuration Task screen, select Set up Database Mail by performing the


following tasks:. Click Next to continue.

4. Next, on the New Profile screen, provide an e-mail Profile Name and an optional description of the


profile, then select the Add button to configure an SMTP Account.

Accenture Proprietary and Confidential Page 7 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

5. On the New Database Mail Account screen, provide the required information for the outgoing mail
server (SMTP). Fill in the Account Name, Description (optional), Email Address, Display name, Reply
Email (optional), and SMTP Server Name and Port number. Then select the appropriate SMTP
authentication for your server and click Next to continue.

6. This will return you to the New Profile screen. Click Next to continue

Accenture Proprietary and Confidential Page 8 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

7. The Manage Profile Security screen allows you to set this profile as either public or private. A
private profile is accessible only to specific users or roles. A public profile allows any user or role with
access to the mail host database (msdb) to send e-mail using this profile. Note that in order to send
Database Mail, users must also be a added to the DatabaseMailUsersRole database role in
the msdb database.

You can also specify that this profile is a default profile. In this case, users or roles can send e-mail
using the profile without explicitly specifying the profile name. If the user or role sending the e-mail
message has a default private profile (use the Private Profiles tab on this screen), Database Mail
uses that profile. If the user or role has no default private profile, sp_send_dbmail uses the default
public profile for the msdb database. If there is no default private profile for the user or role and no
default public profile for the database,sp_send_dbmail returns an error. Only one profile can be
marked as the default profile.

In this instance, check Public and click Next to continue.

Accenture Proprietary and Confidential Page 9 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

8. Use the Configure System Parameters screen to specify Database Mail system parameters such as
retry attempts or types of attachments that you do not want to send out by including the extensions of
the files (Prohibited Attachment File Extensions). Click Next to continue.

9. Finally, review the list of steps the wizard is about to perform, and then click Finish to execute these
actions.

Accenture Proprietary and Confidential Page 10 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

10. Verify that all actions completed successfully. Click Close to exit the Database Mail Configuration
Wizard.

11. Run this query to verify the new profile, sysmail account and accounts of a profile.

Use msdb
Go
--Step1: Varifying the new profile
select * from sysmail_profile
--Step2: Verifying accounts
select * from sysmail_account
--Step3: To check the accounts of a profile
select * from sysmail_profileaccount
where profile_id=1
--Step4: To display mail server details
select * from sysmail_server

Accenture Proprietary and Confidential Page 11 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

12. This should be the result.

13. Perform a quick test of the new e-mail Profile within SQL Server Management Studio. Right-
click Database Mail and select Send Test E-Mail....

Accenture Proprietary and Confidential Page 12 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Sending a Test E-mail

1. Supply a recipient email address and click Send Test E-Mail

2. Check that you received the test email and click Ok to close the dialog box; otherwise click
the Troubleshoot button to investigate any errors.

Accenture Proprietary and Confidential Page 13 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

3. You should receive a test mail like the one below:

4. In addition to the Troubleshooting button, you can also review the contents
of msdb.dbo.sysmail_event_log.

SELECT * FROM msdb.dbo.sysmail_event_log;


Go

Configuring Security in Database Mail

The DatabaseMailUserRole Role

Database Mail is guarded by the database role DatabaseMailUserRole in the msdb database in


order to prevent anyone from sending arbitrary emails. Database users or roles must be created in
the msdb database and must also be a member ofDatabaseMailUserRole in order to send emails with
the exception of sysadmin who has all privileges.

In addition to sp_send_dbmail, the following Database Mail stored procedures and views will be
inaccessible if the user is not a member of DatabaseMailUserRole:

sysmail_help_status_sp
sysmail_delete_mailitems_sp
sysmail_allitems
sysmail_event_log
sysmail_faileditems
sysmail_mailattachments
sysmail_sentitems
sysmail_unsentitems

Accenture Proprietary and Confidential Page 14 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create a User for Database Mail

In order to use Database Mail, the acs login will be created in the msdb database and granted
permission to connect for the acs login. As already mentioned in this section, the user must be a member
of DatabaseMailUserRole in order to send e-mail messages which can be performed
using sp_addrolemember. Next, since the Database Mail profile being used in this guide (SQLADMIN
profile) is a public profile, the new user will need to be granted permissions before the profile can be
used. This is performed using msdb.dbo.sysmail_add_principalprofile_sp. In the example below,
@is_default = 1 is used when calling msdb.dbo.sysmail_add_principalprofile_sp so this profile will be
the default public profile for the new user. Note that each user or role may have only one default profile.

USE [master]
Go

-- Create a user in the [msdb] database

USE [msdb]
Go

CREATE USER [acs] FOR LOGIN [acs];


Go

GRANT CONNECT TO [acs];


Go

--------------------------------------------------------------

USE [msdb]
Go

-- Add user to the Database Mail role


EXEC sp_addrolemember
@rolename = 'DatabaseMailUserRole'
, @membername = 'acs';
Go

-- Grants permission for a database user or role


-- to use a public Database Mail profile
EXEC msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'SQLADMIN
, @principal_name = 'acs'
, @is_default = 1;
Go

Accenture Proprietary and Confidential Page 15 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Send E-Mail from Database Mail

This section provides several examples of how to send messages using Database Mail. The user
sending the messages will be acs.

Send a Simple Text E-Mail Message

This example sends an e-mail message to sample recipients using the e-mail
joan.z.demafelis@accenture.com and donnie.c.ochavillo@accenture.com. The message has the
subject 'Automated Test Results (Successful)'. The body of the message contains the
text'The stored procedure finished successfully.'. Notice that I can be connected to any
database and that the sp_send_dbmail stored procedure is in the msdb database.

USE ACS
Go

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQLADMIN'
, @recipients =
'joan.z.demafelis@accenture.com,donnie.c.ochavillo@accenture.com'
, @subject = 'Automated Test Results (Successful)'
, @body = 'The stored procedure finished successfully.';
Go

You should receive an e-mail like the one below:

Accenture Proprietary and Confidential Page 16 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Send an E-Mail Message with File Attachment

Database Mail uses the Microsoft Windows security context of the current user to control access
to files. Therefore, users who are authenticated with SQL Server Authentication cannot attach files
using @file_attachments. Windows does not allow SQL Server to provide credentials from a remote
computer to another remote computer. Therefore, Database Mail may not be able to attach files from a
network share in cases where the command is run from a computer other than the computer that SQL
Server runs on. 

The following example demonstrates how to send multiple file attachments. When sending
multiple attachments, each file attachment is separated by a semicolon (;). Space are allowed in the file
path so long as the semicolon can delimit each path in the list.

USE ACS
Go

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQLADMIN'
, @recipients =
'joan.z.demafelis@accenture.com,donnie.c.ochavillo@accenture.com'
, @subject = 'Automated Test Results (Successful)'
, @body = 'The stored procedure finished successfully.'
, @file_attachments = 'U:\MSSQL\Files\logo.png;U:\MSSQL\Files\
SQLTestMessage.txt';
Go

Configure Email Notification for SQL Server Agent

After completing the setup and testing of Database Mail, you can optionally select it as your mail
system for the SQL Server agent to send e-mail notifications.

1. This can be configured by launching SQL Server Management Studio, right-click the SQL Server
Agent node in Object Explorer and select Properties.

Accenture Proprietary and Confidential Page 17 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

2. Select the Alert System page in the SQL Server Agent Properties dialog. Check the Enable mail
profile option and choose Database Mail in the Mail system pull-down menu. Next, verify the
correct Mail profile is selected.

3. After configuring the alert system, restart the SQL Server Agent service. If you experience any
problems sending e-mail notifications through the SQL Server Agent, check the service account that
the agent is running under. If the SQL Server Agent is running with one of the built-in accounts like
the Local System account, resources outside the SQL Server machine will be unavailable. This
includes SMTP mail servers that are on other machines. If this is the case, change the service
account for the SQL Server Agent to a domain account to resolve this issue.

Managing Database Mail


How to Start and Stop Database Mail

 Use the msdb.dbo.sysmail_stop_sp system procedure to stop Database Mail. This will stop the
Service Broker objects that the external program uses.  sp_send_dbmail still accepts mail when
Database Mail is stopped using sysmail_stop_sp.

EXEC msdb.dbo.sysmail_stop_sp;
Go

 To start Database Mail, use msdb.dbo.sysmail_start_sp.\

EXEC msdb.dbo.sysmail_start_sp;
Go

Accenture Proprietary and Confidential Page 18 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

 The Database Mail External Program is activated when there are e-mail messages to be processed.
When there have been no messages to send for the specified time-out period, the program exits. To
confirm the Database Mail activation is started, execute the following statement.

EXEC msdb.dbo.sysmail_help_status_sp;
Go

Status
-------
STARTED

 If the Database Mail external program is started, check the status of the mail queue with the following
statement:

EXEC msdb.dbo.sysmail_help_queue_sp @queue_type = 'mail';


Go

queue_type length state last_empty_rowset_time


last_activated_time
---------- ------- ------------------- -----------------------
-----------------------
mail 0 RECEIVES_OCCURRING 2011-04-19 19:41:20.323 2011-04-19
19:40:17.787

The mail queue should have the state of RECEIVES_OCCURRING. The status queue may vary from
moment to moment. If the mail queue state is not RECEIVES_OCCURRING, try stopping the queue
using sysmail_stop_sp and then starting the queue usingsysmail_start_sp.

Archive Database Mail Messages and Event Logs

Copies of Database Mail messages and their attachments are retained in msdb tables along with the
Database Mail event log. Periodically you might want to reduce the size of the tables and remove
messages and events that are no longer needed. The following procedures create a SQL Server Agent
job to automate that process.

Prerequisite: Create a database DBMailArchive with sa as the owner.

1. The first procedure creates a job named Archive Database Mail with five steps. The job will be
run as sa who is the owner of the Database Mail Archive database (DBMailArchive) and
has sysadmin privileges.
2. The first step copies all messages from the Database Mail tables in msdb to a new table in the
Database Mail Archive database and named after the previous month in the
format DBMailArchive_Messages_<year_month>. For example:

DBMailArchive.dbo.DBMailArchive_Messages_2013_2

3. The second step copies the attachments related to the messages copied in the first step, from the
Database Mail tables in msdb to a new table in the Database Mail Archive database and named
after the previous month in the formatDBMailArchive_Attachments_<year_month>. For
example:

DBMailArchive.dbo.DBMailArchive_Attachments_2013_2

Accenture Proprietary and Confidential Page 19 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

4. The third step copies the events from the Database Mail event log that are related to the
messages copied in the first step, from the Database Mail tables in msdb to a new table in the
Database Mail Archive database and named after the previous month in the
format DBMailArchive_Event_Log_<year_month>. For example:

DBMailArchive.dbo.DBMailArchive_Event_Log_2013_2

5. The fourth step deletes the records of the transferred mail items from the Database Mail tables
in msdb using the msdb.dbo.sysmail_delete_mailitems_sp stored procedure.
6. The fifth step deletes the events related to the transferred mail items from the Database Mail
event log table in msdb using the msdb.dbo.sysmail_delete_log_sp stored procedure.
7. The final procedure schedules the job to run at the start of each month.

For this example, the archive tables will be created in a new database named DBMailArchive owned
by sa. The old messages, attachments, and log entries will be moved from the base tables in msdb to the
archive tables. When the job completes, an e-mail message will be sent to operators with the status of the
run. For production use, you might want to consider more robust error checking. Also, if the archived
messages are not required to be stored in a database, they can be exported to a text file, or just deleted.

Create a SQL Server Agent Job

1. In Object Explorer, expand SQL Server Agent, right-click Jobs, and then click New Job.
2. In the New Job dialog box, in the Name box, type Archive Database Mail.
3. In the Owner box, confirm that the job owner is a member of the sysadmin fixed server role. The
job owner in this example will be sa who is the owner of the DBMailArchive database and a
member of the sysadmin fixed server role.
4. In the Category box, click the Database Maintenance.
5. In the Description box, type Archive Database Mail messages, and then click Steps.

Accenture Proprietary and Confidential Page 20 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create a Step to Archive the Database Mail Messages

1. On the Steps page, click New.
2. In the Step name box, type Copy Database Mail Items.
3. In the Type box, select Transact-SQL script (T-SQL).
4. In the Database box, select msdb.
5. In the Command box, type the following statement to create a table named after the previous
month, containing rows older than the start of the current month:

DECLARE @ArchiveDatabaseName NVARCHAR(30) = 'DBMailArchive';


DECLARE @ArchiveSchemaName NVARCHAR(30) = 'dbo';
DECLARE @LastMonth NVARCHAR(12);
DECLARE @CopyDate NVARCHAR(20);
DECLARE @CreateTable NVARCHAR(250);

SET @LastMonth = (SELECT CAST(DATEPART(yyyy,GETDATE()) AS CHAR(4)) + '_'


+ CAST(DATEPART(mm,GETDATE())-1 AS VARCHAR(2)));
SET @CopyDate = (SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP -
DATEPART(dd,GETDATE()-1), 112) AS DATETIME));
SET @CreateTable = 'SELECT * INTO ' + @ArchiveDatabaseName + '.' +
@ArchiveSchemaName +
'.[' + @ArchiveDatabaseName + '_Messages_' +
@LastMonth +
'] FROM sysmail_allitems WHERE send_request_date <
''' +
@CopyDate +
''';';

EXEC sp_executesql @CreateTable;

6. Click OK to save the step.

Accenture Proprietary and Confidential Page 21 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create a Step to Archive the Database Mail Attachments

1. On the Steps page, click New.
2. In the Step name box, type Copy Database Mail Attachments.
3. In the Type box, select Transact-SQL script (T-SQL).
4. In the Database box, select msdb.
5. In the Command box, type the following statement to create an attachments table named after
the previous month, containing the attachments that correspond to the messages transferred in
the previous step:

DECLARE @ArchiveDatabaseName NVARCHAR(30) = 'DBMailArchive';


DECLARE @ArchiveSchemaName NVARCHAR(30) = 'dbo';
DECLARE @LastMonth NVARCHAR(12);
DECLARE @CopyDate NVARCHAR(20);
DECLARE @CreateTable NVARCHAR(250);

SET @LastMonth = (SELECT CAST(DATEPART(yyyy,GETDATE()) AS CHAR(4)) + '_'


+ CAST(DATEPART(mm,GETDATE())-1 AS VARCHAR(2)));
SET @CopyDate = (SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP -
DATEPART(dd,GETDATE()-1), 112) AS DATETIME));
SET @CreateTable = 'SELECT * INTO ' + @ArchiveDatabaseName + '.' +
@ArchiveSchemaName +
'.[' + @ArchiveDatabaseName + '_Attachments_' +
@LastMonth +
'] FROM sysmail_attachments WHERE mailitem_id IN
(SELECT DISTINCT mailitem_id FROM ' +
@ArchiveDatabaseName + '.' + @ArchiveSchemaName + '.
[' + @ArchiveDatabaseName + '_Messages_' +
@LastMonth +
'] )';

EXEC sp_executesql @CreateTable;

6. Click OK to save the step.

Accenture Proprietary and Confidential Page 22 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create a Step to Archive the Database Mail Log

1. On the Steps page, click New.
2. In the Step name box, type Copy Database Mail Log.
3. In the Type box, select Transact-SQL script (T-SQL).
4. In the Database box, select msdb.
5. In the Command box, type the following statement to create a log table named after the previous
month, containing the log entries that correspond to the messages transferred in the earlier step:

DECLARE @ArchiveDatabaseName NVARCHAR(30) = 'DBMailArchive';


DECLARE @ArchiveSchemaName NVARCHAR(30) = 'dbo';
DECLARE @LastMonth NVARCHAR(12);
DECLARE @CopyDate NVARCHAR(20);
DECLARE @CreateTable NVARCHAR(250);

SET @LastMonth = (SELECT CAST(DATEPART(yyyy,GETDATE()) AS CHAR(4)) + '_'


+ CAST(DATEPART(mm,GETDATE())-1 AS VARCHAR(2)));
SET @CopyDate = (SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP -
DATEPART(dd,GETDATE()-1), 112) AS DATETIME));
SET @CreateTable = 'SELECT * INTO ' + @ArchiveDatabaseName + '.' +
@ArchiveSchemaName +
'.[' + @ArchiveDatabaseName + '_Event_Log_' +
@LastMonth +
'] FROM sysmail_event_log WHERE mailitem_id IN
(SELECT DISTINCT mailitem_id FROM ' +
@ArchiveDatabaseName + '.' + @ArchiveSchemaName + '.
[' + @ArchiveDatabaseName + '_Messages_' +
@LastMonth +
'] )';

EXEC sp_executesql @CreateTable;

6. Click OK to save the step.

Create a Step to Remove the Archived Rows from Database Mail

1. On the Steps page, click New.
2. In the Step name box, type Remove Rows from Database Mail.
3. In the Type box, select Transact-SQL script (T-SQL).
4. In the Database box, select msdb.
5. In the Command box, type the following statement to remove rows older than the current month
from the Database Mail tables:

DECLARE @CopyDate NVARCHAR(20);

SET @CopyDate = (SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP -


DATEPART(dd,GETDATE()-1), 112) AS DATETIME));

EXEC msdb.dbo.sysmail_delete_mailitems_sp @sent_before = @CopyDate;

6. Click OK to save the step.

Accenture Proprietary and Confidential Page 23 of 24


DASH_SQL Database Mail_TA423_Installation and
Configuration Guide_v0.1

Create a Step to Remove the Archived Items from Database Mail Event Log

1. On the Steps page, click New.
2. In the Step name box, type Remove Rows from Database Mail Event Log.
3. In the Type box, select Transact-SQL script (T-SQL).
4. In the Database box, select msdb.
5. In the Command box, type the following statement to remove rows older than the current month
from the Database Mail event log:

DECLARE @CopyDate NVARCHAR(20);

SET @CopyDate = (SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP -


DATEPART(dd,GETDATE()-1), 112) AS DATETIME));

EXEC msdb.dbo.sysmail_delete_log_sp @logged_before = @CopyDate;

6. Click OK to save the step.

Schedule the Job to Run at the Start of Each Month

1. In the New Job dialog box, click Schedules.


2. On the Schedules page, click New.
3. In the Name box, type Archive Database Mail.
4. In the Schedule type box, select Recurring.
5. In the Frequency area, select the options to run the job on the first day of every month.
6. In the Daily frequency area, select Occurs once at 3:00:00 AM.
7. Verify that the other options are configured as you wish, and then click OK to save the schedule.
8. Click OK to save the job.

Accenture Proprietary and Confidential Page 24 of 24

You might also like