Sql-server – SQL Server Agent & sp_send_dbmail failing on permissions

database-mailjobssql serversql-server-agent

I have set up a SQL Server Agent job to call sp_send_dbmail with a very simple select on a certain table in a certain database. Within the properties > permissions of the target database, the Database Role 'public' has select permission. The job runs fine, the email arrives, all good.

The problem is, if I turn off the worryingly generous 'public' select permission and try to add the SQLServerAgent user (which is the user the agent is running under and the user that owns the agent job) and give them select permissions, the job fails with this error message:

Failed to initialize sqlcmd library with error number -2147467259.
[SQLSTATE 42000] (error 22050)

Can anyone shed any light on this for me? I suspect that maybe a different user is involved in some way. I cannot get SQL Server Profiler to run (it's not installed) and I don't have access to the server to install it.

Best Answer

It seems that the SQL server agent User has some problem to run sql cmd. It uses sql cmd to run the query to attach in the email.

Please try to to give the agent user the database mail user role. exec sp_addrolemember 'DatabaseMailUserRole', 'domain\agentuser'