In this article I will explain with an example, how to send Email from Trigger 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 and 2017.
I have made use of the following table Customers with the schema as follows.
Send Email from Trigger in SQL Server
I have already inserted few records in the table.
Send Email from Trigger in SQL Server
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.
Send Email from Trigger in SQL Server
Whenever a row is inserted in the Customers Table, the following trigger will be executed. The newly inserted record is available in the INSERTED table.
The following Trigger is fetching the CustomerId of the inserted record and the fetched value is sent through an email.
CREATE TRIGGER [dbo].[Customer_INSERT_Notification]
       ON [dbo].[Customers]
       DECLARE @CustomerId INT
       SELECT @CustomerId = INSERTED.CustomerId      
       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 = ''
           ,@subject = 'New Customer Record'
           ,@body = @body
           ,@importance ='HIGH'
Inserting record in Table
Send Email from Trigger in SQL Server
Received Email
Send Email from Trigger in SQL Server