I’m trying to send an email with HTML file attachment using msdb.dbo.sp_send_dbmail
. The sp sends the email but the attachment has a couple of strange characters added to the start of the file and causing it not to open properly when opened from the email client such as Gmail. I just fount out the first two letters are ÿþ
.
When you try to click the attachment, Gmail says no preview available. If you open the email and double click on the attachment, it opens in text format with the HTML code. The interesting thing is that if I save it to my hard drive then double click on it, it opens fine.
Here is my code:
Declare @html nvarchar(max)
Declare @query nvarchar(max)
set @html = '
<!DOCTYPE html>
<html>
<head>
<style> table td {border: 1px solid #dddddd;text-align: left;padding: 8px;}
th {border: 1px solid #dddddd;text-align: center;padding: 8px;}
.main {bgcolor:#3399ff;background:#3399ff;background-color:#3399ff;}
.numbrs {text-align: right}
</style>
</head>
<body>
<table>
<tr><td class="main">Invoice #</td><td>123456</td>
<td class="main">Invoice Date</td><td>12/31/2022</td>
</table>
</html>
'
Set @query= 'set nocount on; SELECT ''' + @html + ''' AS Results'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'TEST'
,@recipients = 'name@domain.com'
,@subject = 'Test Email with Attachment'
,@body = 'Please see attached file'
,@body_format ='HTML'
,@Query_no_truncate = 1
,@Execute_Query_Database='TEST'
,@query =@query
,@query_attachment_filename = 'Report.html'
,@attach_query_result_as_file = 1
When I double click on the email attachment to open it, it opens as a text in my browser like this:
here is how it should look like if you copy and paste the HTML code in notepad and saved it as a .html file then click on it to open it in a browser:
<!DOCTYPE html>
<html>
<head>
<style>
table td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
}
.main {
bgcolor: #3399ff;
background: #3399ff;
background-color: #3399ff;
}
.numbrs {
text-align: right
}
</style>
</head>
<body>
<table>
<tr>
<td class="main">Invoice #</td>
<td>123456</td>
<td class="main">Invoice Date</td>
<td>12/31/2022</td>
</table>
</html>
Here is how the attachment shows in my browser:
�� <!DOCTYPE html> <html> <head> <style> table td {border: 1px solid #dddddd;text-align: left;padding: 8px;} th {border: 1px solid #dddddd;text-align: center;padding: 8px;} .main {bgcolor:#3399ff;background:#3399ff;background-color:#3399ff;} .numbrs {text-align: right} </style> </head> <body> <table> <tr><td class="main">Invoice #</td><td>123456</td> <td class="main">Invoice Date</td><td>12/31/2022</td> </table> </html>
EDIT: I just fount out the first two letters are ÿþ
which is 0xfffe in UTF-8 according to this SO question.