How to Send Emails from SQL Server (T-SQL)

SQL Server provides the ability to send emails via its Database Mail solution.

The actual act of sending mail is done with the sp_send_dbmail stored procedure. But before you start sending emails from SQL Server, you need to enable and configure Database Mail.

You can do this with the SSMS GUI, or with T-SQL.

This article demonstrates how to do it with T-SQL. It assumes that Database Mail has never been enabled on your system, and therefore it goes through the steps involved in enabling it.

If you prefer to use the SSMS GUI, see How to Setup Database Mail in SQL Server (SSMS).

Continue reading

Delete Database Mail Messages from the msdb Database in SQL Server (T-SQL)

When you use Database Mail to send emails from SQL Server, email messages and their attachments are stored in the msdb database. You should periodically delete these messages to prevent the database from growing to large.

To delete these messages with T-SQL, use the sysmail_delete_mailitems_sp stored procedure.

You can delete mail messages based on their send request date (i.e. before a certain date) or based on their status. You can also delete all mail messages by using the current date as the request date.

Continue reading