sp_send_dbmail fails with attachment

2020-07-11 06:22发布

I need to send email with file attachments. The attachment has to come from image type data field. When running the following code in both a query window and also stored procedure, no email is sent. in query window, it just says 'command(s) completed successfully', but no email.

EXEC  msdb.dbo.sp_send_dbmail @recipients = 'xx@xx.com',
    @subject = 'test',
    @execute_query_database = 'myDB',
    @body = 'test',
    @body_format = 'HTML', 
    @profile_name = 'myProfile',
    @append_query_error = 1,
    @query = 'Select docData from [myDB].[dbo].[Documents] Where id = 1',
    @query_result_header = 0,
    @attach_query_result_as_file = 1,
    @query_attachment_filename = 'Test.doc',
    @exclude_query_output = 1,
    @query_no_truncate = 1;

The email is send when I remove @query:

EXEC  msdb.dbo.sp_send_dbmail @recipients = 'xx@xx.com',
    @subject = 'test',
    @execute_query_database = 'myDB',
    @body = 'test',
    @body_format = 'HTML', 
    @profile_name = 'myProfile';

But I need the attachments code to work. Any help would be greatly appreciated.

2条回答
Evening l夕情丶
2楼-- · 2020-07-11 07:02

Too long to comment.

Change @exclude_query_output = 0 to @exclude_query_output = 1. This will likely print a message (error message) on what is going on.

In your example, I was able to get around the error:

Failed to initialize sqlcmd library with error number -2147024809.

that I got and I expect you'll likely get by changing @query_result_header = 0 to @query_result_header = 1. I'm not sure why the lack of headers is causing it to fail, but it fixed it on my dev box.

查看更多
老娘就宠你
3楼-- · 2020-07-11 07:15

I had the same issue but none of the solutions I found helped. Finally MSSQLTips led me into the right direction. Running profiler I got the following error message:

Could not obtain information about Windows NT group/user 'DOMAIN\user', error code 0x5

Checking the windows security event log for Audit Failures I finally found the reason why:

The specified account's password has expired.

The active directory account which SQL Server and SQL Server Agent ran with had been set up to allow password expiration. Disabling password expiration on the AD account immediately resolved the issue.

查看更多
登录 后发表回答