Sample code for 30+ languages & platforms
SQL Server

Count the Attachments in an Email

See more Email Object Examples

Demonstrates the read-only Chilkat Email.NumAttachments property, which is the number of ordinary attachments in the email. Attachment indexes are zero-based. Related resources inside a multipart/related enclosure are counted separately by NumRelatedItems, and embedded message/rfc822 emails by NumAttachedMessages. This example adds two attachments and prints the count.

Background: An "attachment" is a MIME part meant to be saved or opened as a separate file, as opposed to being displayed as the message body. Chilkat decides whether a part is an attachment by weighing its MIME structure, content type, and Content-Disposition together — so a part can count as an attachment even without an explicit Content-Disposition: attachment header. Note that if an email was downloaded from an IMAP server without its attachment data, this property reflects only what is actually present in the object.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    --  Demonstrates the read-only Email.NumAttachments property, which is the number
    --  of ordinary attachments contained in the email.  Attachment indexes are zero-based.

    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', 'Email with attachments'
    EXEC sp_OASetProperty @email, 'Body', 'Two files are attached.'

    --  Add two string attachments.
    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'readme.txt', 'This is the first attachment.'
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'notes.txt', 'This is the second attachment.'


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

    EXEC @hr = sp_OADestroy @email


END
GO