Sample code for 30+ languages & platforms
SQL Server

Add an Attachment from a BinData Object

See more Email Object Examples

Demonstrates the Chilkat Email.AddAttachmentBd method, which adds an attachment using the contents of a BinData object. The first argument is the attachment filename, the second is the BinData, and the third is the content type — if empty, it is inferred from the filename extension. This example loads a PDF into a BinData and attaches it.

Background: BinData is Chilkat's container for raw binary data. Attaching from a BinData is the right approach when the file's bytes are already in memory — generated on the fly, downloaded, or read from a database — rather than sitting on disk (which would use AddFileAttachment). Chilkat Base64-encodes the bytes into the message automatically.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    --  Demonstrates the AddAttachmentBd method, which adds an attachment using the contents of a
    --  BinData object.  The first argument is the attachment filename, the second is the BinData
    --  object, and the third is the content type (inferred from the filename extension if empty).

    DECLARE @email int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OASetProperty @email, 'Subject', 'Attach from BinData'
    EXEC sp_OASetProperty @email, 'Body', 'Please see the attached file.'

    --  Load a file into a BinData object, then attach it.
    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT

    EXEC sp_OAMethod @bd, 'LoadFile', @success OUT, 'qa_data/attachments/report.pdf'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @bd, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END

    EXEC sp_OAMethod @email, 'AddAttachmentBd', @success OUT, 'report.pdf', @bd, 'application/pdf'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END


    EXEC sp_OAGetProperty @email, 'NumAttachments', @iTmp0 OUT
    PRINT 'NumAttachments = ' + @iTmp0

    --  Note: The path "qa_data/attachments/report.pdf" is a relative local filesystem path,
    --  relative to the current working directory of the running application.

    EXEC @hr = sp_OADestroy @email
    EXEC @hr = sp_OADestroy @bd


END
GO