In this example below the error will occur because the context of the query is running under MSDB when the query is specified without the database name in the query.
The correct query for the above example is:
EXEC msdb.dbo.sp_send_dbmail
@profile_name ='dbMail',
@recipients = 'dharmyog.com@gmail.com',
@subject ='Test Email',
@body ='Test Email',
@query=' select * from [dbo].[vwEmployees] Where EmployeeAge = 25',
@attach_query_result_as_file = 1;
EXEC msdb.dbo.sp_send_dbmail
@profile_name ='dbMail',
@recipients = 'dharmyog.com@gmail.com',
@subject ='Test Email',
@body ='Test Email',
@query=' select * from EmployeeDB.dbo.vwEmployees Where EmployeeAge = 25',
@attach_query_result_as_file = 1;
This way the stored procedure will execute under the msdb context and the query will execute because the database hierarchy is referenced. So the database name has to be entered in the query.