如何使用SQL存储过程将文件附加到电子邮件?

时间:2010-06-22 20:04:54

标签: sql file email dbmail

似乎无法找到有关如何附加作为电子邮件的一部分存储为BLOB的文件的大量信息。

我知道您可以将文件系统(C:\ temp ...)中的文件附加到在DBMAIL或自定义存储过程中设置的电子邮件中。但是,我没有看到任何关于附加诸如PDF的内容的引用,这些内容已作为二进制对象存储在表中。

我知道你可以将查询作为文件附加到哪里,但我认为这不是我要找的。

我们将通过应用程序以编程方式执行此操作,但我们需要能够通过触发器或应用程序的服务器端代码来启动此SP。

这是可能的还是我应该问其他问题,因为通常二进制对象还需要有与之关联的内容类型,以便浏览器或邮件对象知道如何处理?

1 个答案:

答案 0 :(得分:1)

解决方案无法附加存储在db字段中的二进制对象,您可以稍微更改您的模式存储二进制文件的路径。如果你可以在数据库服务器中启用.net clr,你将有更多的选择。

use master
go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_send_cdosysmail]')
and objectproperty(id, N'isprocedure') = 1)
drop procedure [dbo].[usp_send_cdosysmail]
go

create procedure usp_send_cdosysmail
@from varchar(500) ,
@to varchar(500) ,
@subject varchar(500),
@body nvarchar(max) ,
@smtpserver varchar(25),
@bodytype varchar(10) ,
@attachment varchar(100)= ' '
as
declare @imsg int
declare @hr int
declare @source varchar(255)
declare @description varchar(500)
declare @output varchar(1000)
exec @hr = sp_oacreate 'cdo.message', @imsg out
exec @hr = sp_oasetproperty @imsg,
'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").value','2'

exec @hr = sp_oasetproperty @imsg, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").value', @smtpserver 

exec @hr = sp_oamethod @imsg, 'configuration.fields.update', null
exec @hr = sp_oasetproperty @imsg, 'to', @to
exec @hr = sp_oasetproperty @imsg, 'from', @from
exec @hr = sp_oasetproperty @imsg, 'subject', @subject

-- if you are using html e-mail, use 'htmlbody' instead of 'textbody'.

exec @hr = sp_oasetproperty @imsg, @bodytype, @body

-- Attachments...

IF @attachment IS NOT NULL AND LEN(@attachment) > 0 BEGIN
    Declare @files table(fileid int identity(1,1),[file] varchar(255))
    Declare @file varchar(255)
    Declare @filecount int ; set @filecount=0
    Declare @counter int ; set @counter = 1
    DECLARE @outVar INT
    SET @outVar  = NULL

        INSERT @files SELECT cValue FROM master..fn_split(@attachment,',')
        SELECT @filecount=@@ROWCOUNT

        WHILE @counter<(@filecount+1)
        BEGIN
                SELECT @file = [file] 
                FROM @files
                WHERE fileid=@counter

                EXEC @hr = sp_OAMethod @imsg, 'AddAttachment',@outVar OUT, @file

                SET @counter=@counter+1
        END
END

exec @hr = sp_oamethod @imsg, 'send', null

-- sample error handling.
if @hr <>0 
select @hr
begin
exec @hr = sp_oageterrorinfo null, @source out, @description out
if @hr = 0
begin
select @output = ' source: ' + @source
print @output
select @output = ' description: ' + @description
print @output
end
else
begin
print ' sp_oageterrorinfo failed.'
return
end
end
exec @hr = sp_oadestroy @imsg
go
set quoted_identifier off 
go
set ansi_nulls on 
go

sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
GO