Send email from SQL Server

Отправить сообщение на Email с SQL Server

Перед использованием кода, необходимо настроить профиль для отправки почты на SQLServer

USE [MyDB]
GO

ALTER PROCEDURE dbo.SendEmail
@EmailTo nvarchar(100) = 'mail@mail.com'
,@EmailCopy nvarchar(100) = NULL
,@EmailProfile nvarchar(100) = 'EmailProfile'

AS
BEGIN
--BEGIN SP

-- PREAPARE METADATA
IF OBJECT_ID('dbo.SendLog','U') IS NULL
CREATE TABLE dbo.SendLog
(
[Source] nvarchar(100)
,SeqNoOrigin int
,SendDT datetime
)

DECLARE @EmailBody nvarchar(MAX) = ''
,@StartDate DATE = '2023-01-01' -- DATE FROM GET DATA

------------------------
-- GET DATA
IF OBJECT_ID('tempdb..#Items','U') IS NOT NULL
DROP TABLE #Items

SELECT
 SeqNo
,Barcode
,ISNULL(Message, 'EMPTY') as Message
,[status] 
INTO #Items
FROM dbo.int_Items
WHERE [status] = 2
AND CreatedDT >= @StartDate
AND NOT EXISTS (
SELECT TOP 1 1
FROM dbo.SendLog E
WHERE E.Source = 'int_Items'
AND E.SeqNoOrigin = SeqNo
)

-- SEND EMAIL 
IF EXISTS (SELECT TOP 1 1 FROM #Items)
BEGIN

IF ((SELECT COUNT(*) FROM #Items) > 100)
BEGIN
SET @EmailBody = 
N'<H1>TITLE OF MESSAGE:</H1>' +
N'<H2>Items</H2>' +
N'Count of messages more than 100, check it!'
END
ELSE
BEGIN
SET @EmailBody = 
N'<H1>TITLE OF MESSAGE:</H1>' +
N'<H2>Items</H2>' +
N'<table border="1">' +  
N'<tr><th>SeqNo</th><th>Barcode</th><th>Message</th></tr>' +  
CAST ( 
( SELECT
  td = T.SeqNo, '',
  td = T.Barcode, '',
  td = T.Message
  FROM #Items T 
  FOR XML PATH('tr'), TYPE   
) AS NVARCHAR(MAX) ) +  
N'</table>'
END

EXEC msdb.dbo.sp_send_dbmail
    @recipients = @EmailTo,
	@copy_recipients = @EmailCopy,
    @subject =  N'MESSAGE: SUBJECT OF MESSAGE',
    @importance = 'High',
    @body = @EmailBody,
    @body_format = 'HTML',
    @profile_name = @EmailProfile;

-- WRITE LOG
INSERT INTO dbo.SendLog ([Source],SeqNoOrigin,SendDT)
SELECT
'Items'
,SeqNo
,GETDATE()
FROM #Items

END

--END SP
END