Wednesday, 21 November 2018

How to send email from a trigger when a record is inserted

Setting up a trigger using sp_send_dbmail is easier than you think. If you have set up your SQL server to send out emails then it's matter of setting up your email template in the trigger. Have a look at below trigger i have created. 
In this trigger i have first create email body querying from a database query. Then i embed it and send to the recipient that is again queried out from the DB. 
I believe this trigger will save your time :)


USE [Database Name]
GO
/****** Object:  Trigger [dbo].[NotificationEmail]  ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[NotificationEmail]
ON [dbo].[logEvents]
AFTER INSERT 
AS

--Initiation

declare @email varchar(200), @ID varchar(12), @emailBody varchar(500), @emailSubject varchar(150)

--Select email and note

select @email = A.EMAIL, @ID = A.ID
from <DB TABLE> A
      
--Create email strings

set @emailBody = 'A new note has been added to ' + @ID + ', which has triggered an email to ' + @email 
+ char(13) + char(10) + char(10) + 
+'As this ID has been assigned to you, please review the updated information.'+char(10) + char(10) 
+'Thank You'

set @emailSubject = 'New note added to ' + @ID

if @email is not null
begin

--Send email

      EXEC msdb.dbo.sp_send_dbmail
            @profile_name = 'emails',
            @recipients = @email,
            --@recipients = 'sarasidias@test.com',
            @body = @emailBody,
            @subject = @emailSubject
end

No comments:

Post a Comment