sp_send_dbmail attach files stored as varbinary in database

别等时光非礼了梦想. 提交于 2019-12-01 18:21:19
RThomas

I don't think your going to be able to send binary data directly from SQL. There are a few posts out there that talk about this same issue. From the Microsoft documentation a text return to the query is formatted as a text file. Binary is formatted as a hexadecimal. Which as you have pointed out corrupts any file that isn't a text document.

I think you could still accomplish what you're trying to do however by first using BCP to export the binary data out to the file system, and then importing it back in via traditional file attachment methods made available to sendmail.

So something like this. (concept only - untested code)

DECLARE @OutputFileAndPath VarChar(500) = '\\Log_Files\MyFile.pdf ' 
DECLARE @sql VarChar(8000)

SELECT @sql = 'BCP "SELECT MyFile FROM [dbo].[MyTable] 
    WHERE PrimaryKey = 12345" queryout ' + @OutputFileAndPath +
        ' -S MyServer\MyInstance -T -fC:\Documents.fmt'

/* you could use a generic format file that would cover most formats */

EXEC xp_cmdshell @sql, NO_OUTPUT;

while ( (select count(MassEmailID) from MassEmail where status = 20 )>0) 
begin
    select @MassEmailID = Min(MassEmailID) from MassEmail where status = 20
    select @Subject = [Subject] from MassEmail where MassEmailID = @MassEmailID
    select @Body = Body from MassEmail where MassEmailID = @MassEmailID


    exec msdb.dbo.sp_send_dbmail    
        @profile_name = 'MASS_EMAIL',
        @recipients = 'me@myemail.com',
        @subject = @Subject,
        @body =@Body,
        @body_format ='HTML',
        @file_attachments = @OutputFileAndPath /* i.e. \\Log_Files\MyFile.pdf */

    update MassEmailset status= 30,SendDate = GetDate() where MassEmailID = @MassEmailID
end     
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!