Search code examples
sql-servert-sqlsp-send-dbmail

Sending email using sp_send_dbmail() does not work sometimes


I am sending notification email using SQL Server but sometimes emails aren't sent to users.

Here is my SQL table that I store emails which it will be sent to users

CREATE TABLE [dbo].[EmailNotification](
[Id] [INT] IDENTITY(1,1) NOT NULL,
[EmailAdress] [NVARCHAR](50) NULL,
[EmailBody] [NVARCHAR](500) NULL,
[EmailSubject] [NVARCHAR](250) NULL,
[Attachment] [NVARCHAR](500) NULL,
[EmailSent] [BIT] NULL CONSTRAINT [DF_EmailNotification_EmailSent]  DEFAULT 
((0)),
[EmailCreateDate] [DATETIME] NULL CONSTRAINT 
[DF_EmailNotification_EmailCreateDate]  DEFAULT (GETDATE()),
[EmailSentDate] [DATETIME] NULL,
CONSTRAINT [PK_EmailNotification] PRIMARY KEY CLUSTERED 
([Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

And I have created a job which executes this procedure every 1 minute

CREATE PROCEDURE [dbo].[spSendEmail] 
AS
BEGIN
BEGIN TRAN
DECLARE @id BIGINT
DECLARE @max_id BIGINT
DECLARE @query NVARCHAR(1000)
DECLARE @EmailBody NVARCHAR(1000)
DECLARE @EmailAdress NVARCHAR(500)
DECLARE @EmailSubject NVARCHAR(500)
DECLARE @attachments NVARCHAR(1000)

if exists (SELECT * FROM dbo.EmailNotification where EmailSent=0)
begin 
SELECT @id=MIN(id) FROM dbo.EmailNotification where EmailSent=0


SELECT @EmailAdress=EmailAdress,@EmailBody=EmailBody,@EmailSubject=EmailSubject,@attachments=Attachment
FROM EmailNotification WHERE id = @id


exec [msdb].[dbo].[sp_send_dbmail] @profile_name='Notification',
@recipients=@EmailAdress,
@blind_copy_recipients='example.email.com',
@subject=@EmailSubject,
@body=@EmailBody,
@file_attachments=@attachments

end
IF(@@ERROR>0)
BEGIN
ROLLBACK
END
ELSE
BEGIN
UPDATE EmailNotification set EmailSent=1, EmailSentDate=getdate() WHERE Id=@id
COMMIT  
END

Solution

  • What do you mean : spSendEmail is not triggering sp_send_dbmail? sp_send_dbmail is triggered but doesn't do anything....?

    Please get the return code of sp_send_dbmail :
    0 => OK
    <> 0 => Error occured

    DECLARE @result int;
    DECLARE @ErrorNb int;
    EXECUTE @result = exec [msdb].[dbo].[sp_send_dbmail] @profile_name='EDMS email notification',
    @recipients=@EmailAdress,
    @blind_copy_recipients='example.email.com',
    @subject=@EmailSubject,
    @body=@EmailBody,
    @file_attachments=@attachments
    SET @ErrorNb = @@ERROR    
    
    IF @result <> 0
    BEGIN
    -- Something goes wrong
    SELECT @result,@ErrorNb  
    END
    

    You can also use TRY :

    BEGIN TRY
        EXECUTE exec [msdb].[dbo].[sp_send_dbmail] @profile_name='EDMS email notification',
        @recipients=@EmailAdress,
        @blind_copy_recipients='example.email.com',
        @subject=@EmailSubject,
        @body=@EmailBody,
        @file_attachments=@attachments
    END TRY
    BEGIN CATCH
        SELECT ERROR_MESSAGE();
    END CATCH