I am getting this error:
Msg 229, Level 14, State 5, Procedure sp_send_dbmail, Line 1
The EXECUTE permission was denied on the object \'sp_send_dbma
Grant execute permission on sp_send_dbmail
to the user executing the stored procedure, or add them to the role msdb.DatabaseMailUser
.
Found nice and easy fix that worked for me here:
If your SQL applications can’t send email using database mail (I assume you already have DBMail Account and Profile setup), there are two things to set:
Ok, just to add to this topic since this was really good information, but still didn't completely solve my problem. If I ran the query in SSMS, it worked once I was granted permission to execute the sp_send_dbmail procedure in msdb. However, when a job was running as my user, it would still fail.
Read through a lot of stuff to get to the conclusion that you need to make sure the sid for the owner in your DB matches the owner sid in the master DB:
--To get owner SID recorded in the master database for the current database
SELECT owner_sid FROM sys.databases WHERE database_id=DB_ID()
--To get the owner SID recorded for the current database owner
SELECT sid FROM sys.database_principals WHERE name=N'dbo'
Even though I had given access to the msdb and execute rights on the sp_send_dbmail, it was still having issues related to the database being untrustworthy and that the owner sids didn't match. Consequently, I had to the Trustworthy on for the database I was running in and fix the ownership issue:
ALTER DATABASE my_db SET TRUSTWORTHY ON;
ALTER AUTHORIZATION ON Database::my_db TO [domain\user];
I had to go through a lot of ferreting around to finally find this write-up which is much more enlightening.
To send Database mail, users must be a user in the msdb database and a member of the DatabaseMailUserRole
database role in the msdb database. To add msdb users or groups to this role use SQL Server Management Studio or execute the following statement for the user or role that needs to send Database Mail:
EXEC msdb.dbo.sp_addrolemember @rolename = 'DatabaseMailUserRole'
,@membername = '<user or role name>';
GO
I accidentally changed the "Run As" option for the SQL Agent Job - Step from "[User]" to "(Not Specified)". That caused my Job to start working.