Sample code for 30+ languages & platforms
SQL Server

Remove a Single Attachment from an Email

See more Email Object Examples

Demonstrates the Chilkat Email.DropSingleAttachment method, which removes the attachment at the specified zero-based index. Valid indexes run from 0 through NumAttachments - 1. This example adds two attachments, removes the first, and prints the count before and after.

Background: Attachments are addressed by a zero-based index, so the first is 0, the second 1, and so on. DropSingleAttachment removes just one — use it to prune a specific file (say, an oversized or unwanted attachment) while keeping the rest. Note that after a removal the remaining attachments shift down, so if you are deleting several by index, iterate from the highest index downward to avoid skipping any.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    --  Demonstrates the DropSingleAttachment method, which removes the attachment at the
    --  specified zero-based index.

    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', 'Drop a single attachment'

    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'a.txt', 'first attachment'
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'b.txt', 'second attachment'

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

    --  Remove the attachment at index 0 (the first attachment).
    EXEC sp_OAMethod @email, 'DropSingleAttachment', @success OUT, 0


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

    EXEC @hr = sp_OADestroy @email


END
GO