SQL sp_send_dbmail 发送带附件的电子邮件,pdf 文件已损坏

SQL sp_send_dbmail send email with attachment, pdf file got corrupted

我有一个发送电子邮件的存储过程,它会在记录插入到 table 时调用。我想附加一个文件添加到 table 并发送一个 email.I 可以得到附件但是当我打开它时它已损坏(它说文件已损坏)。

谁能帮帮我? 这是代码,为了简单起见,我排除了声明语句。

Select @query = 'set nocount on; select cast(Document as varchar(max)) from dbo.myTable where ID = '+ CAST(@ID as varchar(100))

EXEC msdb.dbo.sp_send_dbmail
  @profile_name = 'Profile1', 
  @recipients = @RecipientEmail,
  @subject = @Subject,
  @body = @Body,
  @importance = 'HIGH',
  @query_attachment_filename = 'att.pdf',
  @attach_query_result_as_file = 1,
  @query_result_no_padding=1,
  @query = @query,
  @query_no_truncate = 1,
  @query_result_header  = 0,
  @exclude_query_output = 0,
  @append_query_error = 1,
  @query_result_width = 32767,
  @body_format ='HTML'

感谢任何帮助。提前致谢。

似乎只支持文本文件作为附件,因为它们的编码方式。如需解决方案和更多信息,您可以查看 this 之前提出的问题。

我能做到这一点的唯一方法是暂时将文件导出到本地文件夹,然后将其附加到电子邮件中。

set @Pid=CAST(@ID as varchar(100)) 
SELECT @query= 'BCP "SELECT Document from myDB.dbo.myTable where ID ='+@Pid+'" queryout "E:\Log_Files\Attached.pdf" -T -N'
        EXEC xp_cmdshell @query; --, NO_OUTPUT;      


  EXEC msdb.dbo.sp_send_dbmail
  @profile_name = 'Profile1', 
  @recipients = @InviteeEmail,
  @subject = @ReferenceNo,
  @body = @PublicationContent,
  @importance = 'HIGH',
  @file_attachments = 'E:\Log_Files\Attached.pdf',
  @body_format ='HTML' --because

END
Go

您可以阅读有关 BCP 实用程序的更多信息 here

使用 SQL 服务器 2014。在 3 部分中给出 table 名称。 servername.dbname.dbo.tblname

DECLARE @Body VARCHAR(8000)
DECLARE @Qry varchar(8000)

SET @Body ='Hi All,'

SET @Qry='set nocount on;select * from tbl_name'

DECLARE
@tab char(1) = CHAR(9)
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'mailid',
@blind_copy_recipients='mailid',
@body= @Body,
@query=@Qry,
@subject='Send db mailer with attachment',
@attach_query_result_as_file = 1,
@query_attachment_filename='filename.xls',
@query_result_separator=@tab,
@query_result_no_padding=1