问题 sp_send_dbmail在主体中嵌入了mhtml文件


我有一个SSRS报告,我需要使用SQL Server中的sp_dbmail存储过程将其嵌入到电子邮件正文中。我可以使用Outlook的前端通过在附加文件时使用“作为文本插入”选项附加SSRS报告的.mhtml导出来执行此操作。

有没有办法可以使用sp_dbmail sproc来做到这一点?

我正在使用SQL Server 2014 Standard


3551
2018-03-17 21:54


起源



答案:


是的,可以通过将文件的内容读入变量,然后将其传递给 sp_send_dbmail。以下是您可以这样做的方法:

declare @htmlBody varchar(max)

SELECT @htmlBody=BulkColumn
FROM   OPENROWSET(BULK N'c:\test\test.html',SINGLE_BLOB) x;



EXEC msdb.dbo.sp_send_dbmail
    @profile_name = N'Email', -- you should use the profile name of yours, whatever is set up in your system.
    @recipients = 'recipient_email_id',
    @subject = 'Test',
    @body = @htmlBody,
    @body_format = 'html',
    @from_address = 'sender_email_id';

这将嵌入内容 c:\test\test.html 进入电子邮件的正文。当然,你可以添加更多的身体。

更新: 

仅当您正在阅读的文件包含时,此方法才有效 HTML 内容。如果你想让它工作 mhtml,你需要转换 mhtml 归档到 html(有关如何转换的详细信息,请参阅@Pops发布的答案 mhtml 至 html)。


6
2018-03-21 10:49



谢谢你的回复。当我尝试你的建议时,它会嵌入.mhtml文件的文本(就像我在记事本中打开它时会看到的)。如果我在IE中打开文件,它不会显示报告。 - Pops
你能发一个最小的例子吗? .mhtml 档案(你的报告)?你有没有设置 @body_format = 'html'? - ahoxha
我知道问题出在哪里。它仅在文件是HTML但不是MHTML时才有效。 - ahoxha
对我而言,它正在努力嵌入HTML模板,这很有用。 - Turik Mirash
太棒了,谢谢。 - Pops


答案:


是的,可以通过将文件的内容读入变量,然后将其传递给 sp_send_dbmail。以下是您可以这样做的方法:

declare @htmlBody varchar(max)

SELECT @htmlBody=BulkColumn
FROM   OPENROWSET(BULK N'c:\test\test.html',SINGLE_BLOB) x;



EXEC msdb.dbo.sp_send_dbmail
    @profile_name = N'Email', -- you should use the profile name of yours, whatever is set up in your system.
    @recipients = 'recipient_email_id',
    @subject = 'Test',
    @body = @htmlBody,
    @body_format = 'html',
    @from_address = 'sender_email_id';

这将嵌入内容 c:\test\test.html 进入电子邮件的正文。当然,你可以添加更多的身体。

更新: 

仅当您正在阅读的文件包含时,此方法才有效 HTML 内容。如果你想让它工作 mhtml,你需要转换 mhtml 归档到 html(有关如何转换的详细信息,请参阅@Pops发布的答案 mhtml 至 html)。


6
2018-03-21 10:49



谢谢你的回复。当我尝试你的建议时,它会嵌入.mhtml文件的文本(就像我在记事本中打开它时会看到的)。如果我在IE中打开文件,它不会显示报告。 - Pops
你能发一个最小的例子吗? .mhtml 档案(你的报告)?你有没有设置 @body_format = 'html'? - ahoxha
我知道问题出在哪里。它仅在文件是HTML但不是MHTML时才有效。 - ahoxha
对我而言,它正在努力嵌入HTML模板,这很有用。 - Turik Mirash
太棒了,谢谢。 - Pops


如果人们想知道,这就是我使用SQL将mhtml转换为html的方式。

declare @source varchar(max), 
@decoded varchar(MAX)

SELECT @source =BulkColumn
FROM   OPENROWSET(BULK N'c:\test\test.mhtml',SINGLE_BLOB) x;

SET @source = SUBSTRING(@source,CHARINDEX('base64',@source,1)+10,LEN(@source))
SET @source = SUBSTRING(@source,1,CHARINDEX('-',@source,CHARINDEX('base64',@source,1)+10)-5)
SET @decoded = cast('' AS xml).value('xs:base64Binary(sql:variable("@source"))', 'varbinary(max)')

EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'Email', -- you should use the profile name of yours, whatever is set up in your system.
@recipients = 'recipient_email_id',
@subject = 'Test',
@body = @decoded,
@body_format = 'html',
@from_address = 'sender_email_id';

4
2018-03-21 17:03