title: sp_send_dbmail Error In Microsoft SQL Agent Job
body: <p>I’m trying to send an email from a scheduled SQL Agent job using sp_send_dbmail and receive the following error:</p>
  
  <p>Msg 22050, Level 16, State 1, Line 0
  Error formatting query, probably invalid parameters
  Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 504
  Query execution failed: Msg 15404, Level 16, State 19, Server MyServer, Line 1
  Could not obtain information about Windows NT group/user 'MyDomain\sqlagent', error code 0x5.</p>
  
  <p>Here is the code from the job step:</p>
  
  <pre><code>DECLARE @SQL NVARCHAR(400)
  SELECT @SQL = 'SELECT COUNT(staff_id) FROM Staff'
  
  EXEC msdb.dbo.sp_send_dbmail
  @recipients = 'me@myemail.com',
  @subject = 'Email Alert',
  @body = 'Test',
  @query = @SQL,
  @execute_query_database = 'MyDB'
  </code></pre>
  
  <p>SQL Agent is running under a domain account [MyDomain\sqlagent].  I granted this user db_owner permission in the MyDB database in addition to adding it as a member of the DatabaseMailUserRole in msdb.  Still no luck.  If I remove the @query and @execute_query_database parameters it will send a ‘test’ email.  However, I need to attach the results from the query.</p>
  
  <p>Any help is appreciated, thanks.</p>