Question

I use sp_send_dbmail to generate and send files that are fed to other program. The program digests "ANSI/ASCII" and "ISO-8859-1" encoding. But I can't get sp_send_dbmail to make one.

Procedure call looks like this

exec msdb.dbo.sp_send_dbmail 
    @profile_name= @profile_name, 
    @recipients  = @recipients,
    @body = @body,
    @subject = @subject,
    @attach_query_result_as_file = 1, 
    @query_result_header = 0,
    @query_result_no_padding = 1,
    @query = @query,
    @query_attachment_filename = @fname,
    @query_result_width = 4000,
    @mailitem_id = @mailitem_id OUTPUT

So the attachment is created from results of passed query. But the resulting file that is actually attached to mail for some reason is encoded with UCS2 Little Endian. Is there a way to change it?

Was it helpful?

Solution

Found workaround that allow to switch between UTF/ANSI. In order to do that you need to modify sp_send_dbmail like that:

  1. Add new parameter to procedure somemthing like @ANSI_Attachment BIT = 0
  2. Replace piece of its code IF(@AttachmentsExist = 1) BEGIN ....... END with

`IF (@AttachmentsExist = 1)

BEGIN
    if (@ANSI_Attachment = 1) 
    begin
        --Copy temp attachments to sysmail_attachments      
        INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
        SELECT @mailitem_id, filename, filesize, 
                convert(varbinary(max), 
                    substring( -- remove BOM mark from unicode
                        convert(varchar(max), CONVERT (nvarchar(max), attachment)), 
                        2, DATALENGTH(attachment)/2
                    )
                )
        FROM sysmail_attachments_transfer
        WHERE uid = @temp_table_uid
    end else begin
        --Copy temp attachments to sysmail_attachments      
        INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
        SELECT @mailitem_id, filename, filesize, attachment
        FROM sysmail_attachments_transfer
        WHERE uid = @temp_table_uid
    end
END `

This does the same but if in procedure call @ANSI_Attachment = 1 is used it removes unicode BOM mark before sending.

Peeked that solution here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top