Sample code for 30+ languages & platforms
SQL Server

Zip an Email's Attachments into One File

See more Email Object Examples

Demonstrates the Chilkat Email.ZipAttachments method, which replaces all of an email's attachments with a single Zip file attachment having the specified filename. The original attachments are removed and packed into the Zip. This example adds two attachments and zips them into one.

Background: Bundling multiple attachments into a single .zip keeps a message tidy, compresses the payload, and works around recipients or gateways that limit the number of attachments. Note that the filename here (files.zip) names the attachment inside the message — it is not a path on disk. The reverse operation is UnzipAttachments.

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 ZipAttachments method, which replaces all of an email's attachments
    --  with a single Zip file attachment having the specified filename.  The original
    --  attachments are removed and packed into the Zip.

    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', 'Zip the attachments'

    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

    --  Replace all attachments with a single Zip attachment named "files.zip".
    EXEC sp_OAMethod @email, 'ZipAttachments', @success OUT, 'files.zip'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END


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

    EXEC @hr = sp_OADestroy @email


END
GO