我有一个名为EMails
的SQL Server表,其中包含列
- Id int,
- 主题nvarchar(100)
- Body nvarchar(MAX),
- 收件人nvarchar(100)
- IsSent位li>
我的应用程序填充它。
我想使用SQL Server发送电子邮件。
我知道如何发送电子邮件
EXEC msdb.dbo.sp_send_dbmail
然而查询
SELECT Subject,Body,Recipient FROM EMails
WHERE IsSent=0
最多可以返回多个
我还希望在邮件发送后将IsSent
设置为1
。
问题:
是否可以使用预定的SQL Server作业。如果是这样,你能提供代码示例吗?
当查询被放入每15分钟运行一次的SQL Server作业时,建议最多发送50封电子邮件
答案 0 :(得分:3)
DECLARE @Subject NVARCHAR(100),
@Body NVARCHAR(MAX),
@Recipient NVARCHAR(100),
@ID INT,
@MailID INT
DECLARE @mails TABLE (ID INT, MailID INT)
DECLARE cur CURSOR FAST_FORWARD READ_ONLY LOCAL FOR
SELECT ID, [Subject], Body, Recipient
FROM dbo.EMails
WHERE IsSent = 0
OPEN cur
FETCH NEXT FROM cur INTO @ID, @Subject, @Body, @Recipient
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name = '....',
@recipients = @Recipient,
@subject = @Subject,
@body = @Body,
@mailitem_id = @MailID OUTPUT
INSERT INTO @mails (ID, MailID)
VALUES (@ID, @MailID)
FETCH NEXT FROM cur INTO @ID, @Subject, @Body, @Recipient
END
CLOSE cur
DEALLOCATE cur
WAITFOR DELAY '00:00:01'
UPDATE u
SET IsSent = 1
FROM dbo.EMails u
JOIN @mails m ON u.ID = m.ID
JOIN msdb.dbo.sysmail_mailitems s ON m.MailID = s.mailitem_id
WHERE s.sent_status = 1
-- failed mails
SELECT s.recipients, s.[subject], s.body, s.sent_status
FROM @mails m
JOIN msdb.dbo.sysmail_mailitems s ON m.MailID = s.mailitem_id
WHERE s.sent_status != 1