Here is a script that you can use in a job. It looks for any jobs that have failed on the current day. You can run this once a day to see what jobs failed on that day. You can add a time variable if you want to run this every 30 minutes or so and only see the jobs which failed within the last hour. You have to be able to use xp_cmdshell
which i assumed you would be able to since you want to use sp_send_dbmail
declare @filepath nvarchar(100) --file path where results are stored as csv
declare @filename nvarchar(100) --file name where results are stored
declare @command nvarchar(4000) --dynamic sql of bcp command
declare @count int --result count
declare @emailList varchar(4000) --people to email
declare @dt int --current date in INT format
set @filepath = '"e:\somefolder\'
set @filename = 'Failures.csv"'
set @emailList = 'email@domain.com; someOtherEmail@domain.com'
set @dt = (select convert(int,replace(convert(date,substring(convert(varchar,getdate()),1,11)),'-','')))
--query to get the jobs that failed and why. Looks for jobs that were executed today.
select
h.run_date,
h.run_time,
h.run_status,
j.name,
j.description,
h.message
from
msdb.dbo.sysjobhistory h
inner join
msdb.dbo.sysjobs j on j.job_id = h.job_id
where
h.run_status = 0
and h.run_date = @dt
--if there were failures then put them in a csv and email them.
set @count = @@ROWCOUNT
if (select @count) > 0
begin
set @command = 'bcp "select h.run_date, h.run_status, j.name, j.description, h.message from msdb.dbo.sysjobhistory h inner join msdb.dbo.sysjobs j on j.job_id = h.job_id where h.run_status = 0 and h.run_date = convert(int,''' + convert(varchar,@dt) + ''') " queryout '
set @command = @command + @filepath + @filename + ' -c -t, -T '----> character data, tab delimtted is default use -t, for comma ... trusted conn,server instance to connect to
exec master..xp_cmdshell @command
exec msdb.dbo.sp_send_dbmail
@profile_name = null,
@recipients = @emailList,
@body = 'Attached is the job failure results',
@body_format = 'TEXT',
@subject = 'Job Failures',
@file_attachments = 'e:\someFolder\Failures.csv'
end