2010-06-22 131 views
1

似乎無法找到關於如何附加存儲爲BLOB的文件作爲電子郵件的一部分的很多信息。如何使用SQL存儲過程將文件附加到電子郵件?

我知道你可以將文件從文件系統(C:\ temp ...)附加到正在DBMAIL或自定義存儲過程中設置的電子郵件。但是,我還沒有看到任何關於附加諸如作爲二進制對象存儲在表格中的PDF的引用。

我看到你可以附加一個查詢作爲一個文件,但我不認爲這就是我要找的。

我們會通過應用程序編程做到這一點,但我們需要能夠通過觸發器或應用程序的服務器端代碼踢這個SP。

這是可能的,或者我應該會問其他問題,因爲通常一個二進制對象也需要有它的瀏覽器或郵件對象相關聯的內容類型,知道如何處理?

回答

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 @[email protected]@ROWCOUNT 

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

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

       SET @[email protected]+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 
相關問題