检查使用数据库邮件发送的电子邮件的状态

适用于:SQL ServerAzure SQL 托管实例

本文介绍如何使用 Transact-SQL 检查使用 SQL Server 中的数据库邮件发送的电子邮件的状态。

  • 数据库邮件会保留传出电子邮件的副本,并在数据库msdb的视图sysmail_allitemssysmail_sentitemssysmail_unsentitemssysmail_faileditems中显示它们。
  • 数据库邮件外部程序记录活动,并通过 Windows 应用程序事件日志和数据库中的sysmail_event_logmsdb视图显示日志。
  • 电子邮件可以处于下列四种可能的状态之一: sentunsentretryingfailed

若要检查电子邮件的状态,请针对 msdb.dbo.sysmail_event_log 系统视图运行查询。

使用 Transact-SQL 查看使用数据库邮件发送的电子邮件的状态

  • sysmail_allitems表中选择,按mailitem_idsent_status指定感兴趣的消息。

  • 若要检查从外部程序返回的电子邮件消息的状态,请在mailitem_id列中加入sysmail_allitemssysmail_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