So just a quick one today. I was recently working on a SQL Server, running through some Database Mail setup and testing (see Microsoft Docs) with one of our applications. I needed a way to see what e-mails were being sent out as well as what wasn’t. The below queries will give you the info I was after, the first one shows any items that have run through DB Mail and their details for the last day (you can customise the WHERE statement to your needs. You will want to run them against MSDB, do this by selecting it or issuing a USE MSDB statement.
SELECT p.name, i.send_request_date, i.sent_date, i.recipients, i.subject, i.body FROM sysmail_mailitems AS i inner join sysmail_profile as p on p.profile_id = i.profile_id WHERE sent_date > DATEADD(DAY, -1,GETDATE())
Bare in mind that I’m using Aliases to shorten the query a little (see this article). Now this next one simply shows failed items as well as error responses if any from a mail server.
SELECT i.subject, i.recipients, i.copy_recipients, i.blind_copy_recipients, i.last_mod_date, l.description FROM sysmail_failedi AS i LEFT OUTER JOIN sysmail_event_log AS l ON i.mailitem_id = l.mailitem_id WHERE (i.last_mod_date > DATEADD(DAY, - 1, GETDATE()))
Hope that helps.