I have two questions related to sending query results as attachments using sp_send_dbmail.
Problem 1: Only the main .txt files are opened. Any other format, such as .pdf or .jpg, is corrupted.
Problem 2: When I try to send multiple attachments, I get one file with all the file names glued together.
I am running SQL Server 2005, and I have a table in which the downloaded documents are stored:
CREATE TABLE [dbo].[EmailAttachment](
[EmailAttachmentID] [int] IDENTITY(1,1) NOT NULL,
[MassEmailID] [int] NULL, -- foreign key
[FileData] [varbinary](max) NOT NULL,
[FileName] [varchar](100) NOT NULL,
[MimeType] [varchar](100) NOT NULL
I also have a MassEmail table with standard emails. Here is the SQL Send Mail script. For brevity, I excluded the announcement statements.
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
set @query = 'set nocount on; select cast(FileData as varchar(max)) from Mydatabase.dbo.EmailAttachment where MassEmailID = '+ CAST(@MassEmailID as varchar(100))
select @filename = ''
select @filename = COALESCE(@filename+ ',', '') +FileName from EmailAttachment where MassEmailID = @MassEmailID
exec msdb.dbo.sp_send_dbmail
@profile_name = 'MASS_EMAIL',
@recipients = 'me@myemail.com',
@subject = @Subject,
@body =@Body,
@body_format ='HTML',
@query = @query,
@query_attachment_filename = @filename,
@attach_query_result_as_file = 1,
@query_result_separator = '; ',
@query_no_truncate = 1,
@query_result_header = 0;
update MassEmailset status= 30,SendDate = GetDate() where MassEmailID = @MassEmailID
end
I can successfully read files from the database, so I know that binary data is not corrupted.
.txt FilaData varchar. . , . , . , , mimetype - ?
, , coalesce , . . , !