sp_send_dbmail executed from job fails with query result attached as file

I have faced with the following issue: when trying to send email with results of query attached as file, using sp_send_dbmail via executing ordinary query everything seems to be working OK.

But if add the same code into JobStep and run the job, it fails.

  • Passing an array/table to stored procedure through Entity Framework
  • Table column split to two columns in sql?
  • How to remove lowercase letters from varchar
  • How to get the next number in a sequence
  • SQL with most current position and weight
  • In SSIS, how do I get the number of rows returned from the Source that SHOULD be processed
  • Error in job history says

    Error formatting query, probably invalid parameters [SQLSTATE 42000] (Error 22050). The step failed.

    But when I comment out parameter that refers to file attaching it starts working correctly again.

    exec msdb.dbo.sp_send_dbmail 
        @profile_name = 'profile_name', 
        @recipients  = 'some@mail.com',
        @body = 'body',
        @subject = 'subj',
        --Parameters that refers to attached file
        @attach_query_result_as_file = 1, 
        @query_result_header = 0,
        @query_result_no_padding = 1,
        @query = 'select 1',
        @query_attachment_filename = 'test.csv'
    

    Any suggestions?

  • How can I attach a PDF file stored as binary object in SQL Server to an email?
  • 8 Solutions collect form web for “sp_send_dbmail executed from job fails with query result attached as file”

    I’ve come to workaround of that issue. Don’t know why would it work but never the less. 🙂
    It is definitely about security.

    I’ve investigated that SQL Agent is running on behalf of domain user, say DOMAIN\User.
    It has full set of admin rights on server (‘sysadmin’ server role, etc). SQL Server itself is running under that same user.

    The step of job that contains call to sp_send_dbmail runs under the same DOMAIN\User.

    Also I’ve traced that when running the query part of sp_send_dbmail it tries to execute
    exec xp_logininfo ‘DOMAIN\User’ to check against Active Directory if that user is OK. And surprise: something is definitely not OK. This check ends up with:

    Msg 15404, Level 16, State 19, Server SQLC002INS02\SQLC002INS02, Line 1
    Could not obtain information about Windows NT group/user 'DOMAIN\User.', error code 0x2.
    

    That, with some probability can mean anything about that user’s password is expired or user is locked or any other non pleasant things for that guy.

    I decided that its to risky to change user for Agent. So I come up to sending mail on behalf of ‘sa’ which has same ‘sysadmin’ server role but SQL authorization and omits this AD checking step.

    It looks like one user that pretends to be admin to ask the real admin to run dangerous code for him 🙂

    So final code of this job’s the first and the only step resembles this:

    execute as login = 'sa'
    exec msdb.dbo.sp_send_dbmail 
        @profile_name = 'profile_name', 
        @recipients  = 'some@mail.com',
        @body = 'body',
        @subject = 'subj',
        --Parameters that refers to attached file
        @attach_query_result_as_file = 1, 
        @query_result_header = 0,
        @query_result_no_padding = 1,
        @query = 'select 1',
        @query_attachment_filename = 'test.csv'
    revert
    

    I had this problem. I am using SQL Server 2008 R2. I got the email sent with more info about the error by adding option:

    @append_query_error = 1,
    

    I got the email with this error about permissions instead of my query:

       Msg 916, Level 14, State 1, Server SERVER\INST01, 
    Procedure GetSalesReport, Line 62
    The server principal "CONTROLLEDNETWO\sql.service" is not able 
    to access the database "MYDB01" under the current security co
    ntext.
    

    My query was trying to access some tables where SQL Agent had no permissions (actually in my case it has not even access to it).

    I fixed it through SQLSMS by adding a new user “CONTROLLEDNETWO\sql.service” to the db “MYDB01” and granting permissions to “select”.

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'Main Profile',
        @recipients = 'me@vwp.com',
        @subject = 'Test',
        @body = 'this is a test',
        @execute_query_database = 'myTargetDatabase_mscrm',
        @query = N'SELECT * from myTargetDatabase_mscrm.dbo.SystemUserBase',
        @attach_query_result_as_file = 1,
        @query_attachment_filename = 'Test.txt'
    

    For reference, this failed repeatedly showing as invoked as the domain administrator, but run as local\sqladmin. After flipping variables off an on and trying to give permissions, I saw in the script of the job that it was still using the master database. I found the setting staring me in the face. It’s in the configuration for the Step. I changed it to msdb and it worked. Keep in mind that I changed the select from myTable to select from myDatabase.dbo.myTable based on some posts. That may or may not have contributed to fixing the problem. I also used @execute_query_database to make sure it’s running the query from the right place. Again, that might not have been necessary.

    No matter what finally made it happy, it had nothing to do with whether it was attaching or not.

    When you manually execute your query, YOUR credentials are used. When SQL Agent executes the same query, the SQL Agent service account’s credentials are used. By default, SQL Server Agent will use the LocalSystem account credentials. One way to fix the problem would be to change the user under which the SQL Server Agent service is running with a user that has access to your csv directory\file.

    I believe this problem was due to a change implemented in SQL 2008 and later regarding locking down security for just the sp_send_dbmail.
    It only happens if you pass a qry to send_dbmail to execute, and return the results thru the email. The problem is the error message is misleading and not appropriate.
    A good solution is to create a SQL user with just the minimum necessary permissions to perform that query. For example, db_reader, or db_writer, and db_owner if absolutely necessary. And make that user the owner. You can also create a SQL credential and configure that sql job to run under that SQL credential.

    I had this problem too, and solved it in two parts using much of the advice here.

    1) Right-click, ‘View History’ on the job showed failure details, and the failure notice gave the name of the user the job ran under, so I gave this user read-only access to my DB.

    2) I had forgotten to specify DBName.dbo.MyTableName and was using MyTableName only.

    Incidentally, the emails were all going to my junk email folder.

    This was all helpful thank you. Wanted to share what I was trying to do with the excel(xls) attachment which was put the results in columns. This worked for me by adding the query_result_no_padding = 1, and query_result_separator= ‘ , ‘. ( that is a Tab,Tab in the ticks )

    @query_result_header= 1,
    @attach_query_result_as_file = 1,
    @query_result_no_padding = 1,
    @query_attachment_filename = 'TestPriceFlingerReport.xls',
    @query_result_separator= '  ,   ',
    @profile_name = 'Test Exchange Server'
    

    in my situation, It could not identify the table belongs to with database. Once the database.dbo.table was added to the query it worked.

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.