I'm working on a piece of code that will email me the results of some queries twice a day from SQL Server 2016. When I run this bit of code from my developer window, it works fine. When I run it from the job, I get this error:
Executed as user: myDB\svcAGCRM2016_PRD. Failed to initialize sqlcmd
library with error number -2147467259. [SQLSTATE 42000] (Error 22050).
The step failed.
This is the code that runs:
declare #recipient_name varchar(500)
declare #SqlQuery varchar(max)
SET #SqlQuery='exec [myDB].[dbo].[sp_DailyRejectionRate]'
set #recipient_name = 'myemail#email.com'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMTPProfile',
#recipients =#recipient_name,
#subject = '[INFO]'
,#query='exec [myDB].[dbo].[sp_DailyRejectionRate];
I'm running this from a service account. Weirdly, not with the name of the service account in the error. Actually, I can't even find that account.
In the code, I'm doing an exec because otherwise the query is too long for query.
The service account that runs this is an SA. Also, I wrote another query this morning that sends out email with not problems today.
Any ideas?
What if you explicitly specify the user in the query string?
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMTPProfile',
#recipients =#recipient_name,
#subject = '[INFO]'
,#query='execute as user='my_sa_user' exec [myDB].[dbo].[sp_DailyRejectionRate];
Related
Using SQL-Server 2019; I am trying to use sp_send_dbmail and have successfully sent test emails from SQL-Server so believe the configuration is fine.
A sproc runs in the execution context of a SQL-Login, which updates some tables in a database and then calls the sproc below which is supposed to send emails via msdb.dbo.sp_send_dbmail.
CREATE PROCEDURE [dbo].[sp_SendEmail]
#emailAddress AS NVARCHAR(MAX),
#emailBody AS NVARCHAR(MAX),
#emailSubject AS NVARCHAR(150),
#attachmentPath AS NVARCHAR(255) = NULL,
#emailId AS INT OUTPUT
WITH EXECUTE AS N'Bob'
AS
BEGIN
SET NOCOUNT ON;
DECLARE #bSuccess AS INT = 0;
EXECUTE #bSuccess = [msdb].[dbo].[sp_send_dbmail]
#profile_name = N'Profile',
#recipients = #emailAddress,
#subject = #emailSubject,
#body = #emailBody,
#body_format = N'HTML',
#importance = N'High',
#file_attachments = #attachmentPath,
#mailitem_id = #emailId OUTPUT;
RETURN #bSuccess;
END
GO
When I run the sproc I get the error:
Msg 229, Level 14, State 5, Procedure msdb.dbo.sp_send_dbmail, Line 1
[Batch Start Line 2] The EXECUTE permission was denied on the object
'sp_send_dbmail', database 'msdb', schema 'dbo'.
The SQL-Login, Bob, has a user mapping to the msdb database using the default schema and is a member of the DatabaseMailUserRole role.
I've given Bob execute permission on the sp_send_dbmail securable, which seems like a duplication of what the DatabaseMailUserRole provides, but still get the error above.
I'd appreciate any insight you can throw at me.
I am using sp_send_dbmail to send an email containing entries in table Persons. It throws following error -
Failed to initialize sqlcmd library with error number -2147467259.
My query is below -
declare #q varchar(max)
SET #q='SELECT FirstName,LastName FROM dw_extract.dbo.Persons'
USE msdb
EXEC sp_send_dbmail
#profile_name = 'profile_name',
#recipients = 'abc#xyz.com',
#subject = 'T-SQL Query Result',
#body = 'The result from SELECT is appended below',
#execute_query_database = 'dw_extract',
#query = #q
I did some research and found that few people who faced such problem could get rid of it by explicitly stating column names and database of the table used. I did that but still it continues to throw the error.
I followed a guide online, to send a mail through SQL Server Express, but it keeps saying "Mail (Id: 1) queued.", and up to 17, as I have tried 17 times now.
The email is a dummy mail, and not my real one. It is just an example. I use my real mail in the SQL Server Management Studio. SQL Server Express as my teacher called it.
First part of code (To create sysmail account)
EXECUTE msdb.dbo.sysmail_add_account_sp
#account_name = 'MailTest',
#description = 'Sent Mail using MSDB',
#email_address = 'testmail#mail.com',
#display_name = 'Landlyst',
#username='testmail#mail.com',
#password='password',
#mailserver_name = 'mail.google.com'
Second part of code (To create Database Profile)
EXECUTE msdb.dbo.sysmail_add_profile_sp
#profile_name = 'MailTest',
#description = 'Profile used to send mail'
Third part of code (To add database Mail account to profile)
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
#profile_name = 'MailTest',
#account_name = 'MailTest',
#sequence_number = 1
Fourth part of code (Grants permission to all)
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
#profile_name = 'MailTest',
#principal_name = 'public',
#is_default = 1 ;
Fifth part of code (to enable the program to send mail, and not give an error)
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO
Sixth part of code (To send the test mail)
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'MailTest',
#recipients = 'receiver#queryingsql.com',
#subject = 'Mail Test',
#body = 'Mail Sent Successfully',
#body_format = 'text'
I am not very good at SQL, but I need this to work as a trigger on a user.
Could someone please help me with this?
Source
I ran all the same commands you did (with the profile name of 'admin') and my msdb.dbo.sysmail_log table was still empty. I additionally followed step 5 in this link which suggests running the command below (back up the registry first). I did a search in the registry to find where UseDatabaseMail and DatabaseMailProfile were. However, the command did not work, so I changed the values manually in the registry.
USE msdb
GO
EXEC master.dbo.xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL13.SQLEXPRESS\SQLServerAgent',
N'UseDatabaseMail',
N'REG_DWORD', 1
EXEC master.dbo.xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL13.SQLEXPRESS\SQLServerAgent',
N'DatabaseMailProfile',
N'REG_SZ',
N'admin'
However, this also did send my queued mail. This link suggested trying to run the Databasemail.exe directly. I searched for 'databasemail' which was in 'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Binn'. and ran as administrator. I got the error, "The following feature couldn't be installed: .NET Framework 3.5 (includes .NET 2.0 and 3.0)"
Once .NET 3.5 was successfully installed, my queued mail was sent!
I'm trying to use sp_send_dbmail to send the results of a query through a SQLAgent job in SQL Server 2014. I believe I have my DBMail profile set up properly but when running this:
exec msdb.dbo.sp_send_dbmail
#profile = 'TestProfile',
#recipients = 'testmail#gmail.com',
#subject = 'Test',
#query = 'SELECT id FROM TestTable',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'TestValues.txt'
I get the following error message:
Failed to initialize sqlcmd library with error number -2147467259.
Googling this error message didn't turn up anything useful, likely due to the generic error number. Anyone have some insight into this error message?
I found that despite both my query window (for testing) and SqlAgent job were pointing at my desired DB, sp_send_dbmail doesn't seem to have any database context. My original post was failing because SQL didn't know where to run SELECT * FROM TestTable. The fix is to provide sp_send_dbmail with database context by either fully qualifying your table in the #query parameter:
#query = 'SELECT id FROM testDB.dbo.TestTable'
or by providing the optional #execute_query_database parameter:
#execute_query_database = 'testDB'
Enable sysadmin server role for the account that is used to run the SQL Server Agent.Below are the screenshots.
Error
Fix
Now the SQL Server Job runs without any errors and I get an email from dbmail.
There's another reason why you might get this error; if the query has an issue.
In our case we had (note that it's not due to a syntax error; note the missing quotes):
DECLARE #EmailQuery varchar(max) = 'select
e.Field1,
REPLACE(REPLACE(e.ExceptionReason, CHAR(13), ''), CHAR(10), '') ExceptionReason,
e.UserName
from dbo.tblException e'
Once we corrected it as follows, it worked fine:
DECLARE #EmailQuery varchar(max) = 'select
e.Field1,
REPLACE(REPLACE(e.ExceptionReason, CHAR(13), ''''), CHAR(10), '''') ExceptionReason,
e.UserName
from dbo.tblException e'
I’m trying to send an email from a scheduled SQL Agent job using sp_send_dbmail and receive the following error:
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.
Here is the code from the job step:
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'
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.
Any help is appreciated, thanks.
I've run into some strange errors with AD in the past. I would recommend checking that the account you are running this under has it's attributes readable within AD. The quickest way to do that would be to run
exec xp_logininfo 'MyDomain\sqlagent'
and seeing if you get the same error. If you do, check the security properties of the domain account [right click the user in Active Directory > Properties > Security tab] and set Read permissions for Authenticated Users.
This worked for me.
'SELECT columnname from YourDatabase.SchemaName.tablename'
I found this answer here.
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7869b033-80f1-4594-a77e-fb6dce582fb4/error-msg-when-sending-email-using-spsenddbmail?forum=transactsql