SQL Server stores all mails and attachments in msdb database. To avoid unnecessary growth of msdb database you should remove these mail history unless it is required for auditing or other purposes.
To check all mails processed by Database Mail, you can use sysmail_allitems catalog view:
SELECT COUNT(*)
FROM msdb.dbo.sysmail_allitems
Output:
———–
125
There are 3 siblings of this catalog view sysmail_faileditems, sysmail_unsentitems and sysmail_sentitems which shows mails of different status respectively.
If you are frequently sending larger attachments using database mail this can cause msdb to grow rapidly. All attachments stored in msdb database are available in sysmail_attachments.
To delete mail items you can use system stored procedure sysmail_delete_mailitems_sp, it has below syntax:
sysmail_delete_mailitems_sp [@sent_before] [@sent_status]
You can delete mail using either of the parameters, @sent_before deletes all mail that were sent before specified date, and @sent_status deletes all mails with specified status.
For example, to delete all mails which are sent and are older than current month we can use:
EXEC msdb.dbo.sysmail_delete_mailitems_sp
@sent_before = '2012-05-10 00:00:00',
@sent_status = 'sent'
Output:
(100 row(s) affected)
You can query the sysmail_event_log view to check the deletions that has been initiated.
SELECT description
FROM sysmail_event_log
ORDER BY log_date DESC
Output:
description
Mail items deletion is initiated by user “sa”. 100 items deleted.
DatabaseMail process is started
Hope This Helps!
Vishal
If you like this post, do like my Facebook Page -> SqlAndMe
EMail me your questions -> Vishal@SqlAndMe.com
Follow me on Twitter -> @SqlAndMe
Filed under: Catalog Views, Database Mail, SQLServer