Sample code for 30+ languages & platforms
SQL Server

Save a Single Email Attachment to Disk

See more Email Object Examples

Demonstrates the Chilkat Email.SaveAttachedFile method, which saves the attachment at a given zero-based index to a directory. If the directory or any of its components do not exist, Chilkat creates them. This example adds an attachment and saves it.

Background: Where SaveAllAttachments writes every attachment at once, SaveAttachedFile saves just one by index — useful when you have inspected the attachments (by type, name, or size) and want to extract only a specific file. The attachment keeps its own filename; the same filename-safety considerations apply as when saving all of them.

Chilkat SQL Server Downloads

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

    --  Demonstrates the SaveAttachedFile method, which saves the attachment at a given
    --  zero-based index to a directory.  If the directory (or any of its components) does not
    --  exist, Chilkat creates it.

    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', 'Save one attachment'

    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'report.txt', 'Attachment content.'

    --  Save the attachment at index 0 into the specified directory.
    EXEC sp_OAMethod @email, 'SaveAttachedFile', @success OUT, 0, 'qa_output/attachments'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END


    PRINT 'Saved attachment 0.'

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

    EXEC @hr = sp_OADestroy @email


END
GO