In this article I will explain with an example, how to send email when Table is updated in
SQL Server.
This article will illustrate how to send email from
Trigger using
sp_send_dbmail Stored Procedure in
SQL Server by using GMAIL SMTP settings.
This article is applicable to following
SQL Server versions i.e. 2008, 2008R2, 2012, 2014, 2016, 2017, 2019 and 2022.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Download SQL file
Configuring SQL Server for sending emails
In order to send emails from
SQL Server, the
SQL Server needs to be configured. The details of configuration are covered in the following article.
Sending Email when Table is updated in SQL Server
When a new row or record is inserted in the Customers table, the following Trigger will be executed.
The CustomerId of the newly inserted record is available in the INSERTED table.
The following
Trigger fetched the
CustomerId of the inserted record is sent through an email using
sp_send_dbmail Stored Procedure.
CREATE TRIGGER [dbo].[Customer_INSERT_Notification]
ON [dbo].[Customers]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CustomerId INT
SELECT @CustomerId = INSERTED.CustomerId
FROM INSERTED
declare @body varchar(500) = 'Customer with ID: ' + CAST(@CustomerId AS VARCHAR(5)) + ' inserted.'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Mudassar_Email_Profile'
,@recipients = 'recipient@gmail.com'
,@subject = 'New Customer Record'
,@body = @body
,@importance ='HIGH'
END
Screenshots
Inserting record in Table
Received Email
Downloads