使用sp_send_dbmail()发送电子邮件有时不起作用

时间:2017-09-30 08:49:38

标签: sql-server tsql sp-send-dbmail

我正在使用SQL Server发送通知电子邮件,但有时电子邮件不会发送给用户。

这是我存储的电子邮件的SQL表,它将发送给用户

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]

我创建了一个每1分钟执行一次此程序的工作

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

1 个答案:

答案 0 :(得分:2)

你是什么意思:spSendEmail没有触发sp_send_dbmail? sp_send_dbmail被触发但没有做任何事情......?

请获取sp_send_dbmail的返回码:
0 => OK
<> 0 =>发生错误

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

您也可以使用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