本文介绍如何使用 Transact-SQL 检查使用 SQL Server 中的数据库邮件发送的电子邮件的状态。
- 数据库邮件会保留传出电子邮件的副本,并在数据库
msdb
的视图sysmail_allitems
、sysmail_sentitems
、sysmail_unsentitems
、sysmail_faileditems
中显示它们。 - 数据库邮件外部程序记录活动,并通过 Windows 应用程序事件日志和数据库中的
sysmail_event_log
msdb
视图显示日志。 - 电子邮件可以处于下列四种可能的状态之一: sent、 unsent、 retrying和 failed。
若要检查电子邮件的状态,请针对 msdb.dbo.sysmail_event_log
系统视图运行查询。
使用 Transact-SQL 查看使用数据库邮件发送的电子邮件的状态
从
sysmail_allitems
表中选择,按mailitem_id
或sent_status
指定感兴趣的消息。若要检查从外部程序返回的电子邮件消息的状态,请在
mailitem_id
列中加入sysmail_allitems
和sysmail_event_log
视图。默认情况下,外部程序不会记录有关发送成功的邮件的信息。 若要记录所有邮件,请使用 “数据库邮件配置向导” 的 “配置系统参数”页,将日志级别设置为“详细”。
下面的示例列出了有关发送到 danw
的所有电子邮件(外部程序无法成功发送)的信息。 该语句列出了邮件的主题、外部程序发送邮件失败的日期和时间以及来自数据库邮件日志的错误消息。
USE msdb ;
GO
-- Show the subject, the time that the mail item row was last
-- modified, and the log information.
-- Join sysmail_faileditems to sysmail_event_log
-- on the mailitem_id column.
-- In the WHERE clause list items where danw was in the recipients,
-- copy_recipients, or blind_copy_recipients.
-- These are the items that would have been sent
-- to danw.
SELECT items.subject,
items.last_mod_date
,l.description
FROM dbo.sysmail_faileditems AS items
INNER JOIN dbo.sysmail_event_log AS l
ON items.mailitem_id = l.mailitem_id
WHERE items.recipients LIKE '%danw%'
OR items.copy_recipients LIKE '%danw%'
OR items.blind_copy_recipients LIKE '%danw%';
GO