Sample code for 30+ languages & platforms
SQL Server Requires Chilkat v11.0.0+

Read an attached email

See more Email Object Examples

Open forward-as-attachment.eml from the forwarding example. Read the cover note’s subject, then open each attached message and inspect its own headers and attachment count. This works even when the outer message has no ordinary files.

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

    --  Assumes Chilkat is unlocked. See Global Unlock Sample.

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

    EXEC sp_OAMethod @wrapper, 'LoadEml', @success OUT, 'forward-as-attachment.eml'
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @wrapper, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @wrapper
        RETURN
      END

    EXEC sp_OAGetProperty @wrapper, 'Subject', @sTmp0 OUT
    PRINT 'Cover note: ' + @sTmp0
    EXEC sp_OAGetProperty @wrapper, 'NumAttachedMessages', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN

        PRINT 'No attached messages.'
        EXEC @hr = sp_OADestroy @wrapper
        RETURN
      END
    DECLARE @nested int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @nested OUT

    DECLARE @i int
    SELECT @i = 0
    EXEC sp_OAGetProperty @wrapper, 'NumAttachedMessages', @iTmp0 OUT
    WHILE (@i < @iTmp0)
      BEGIN
        EXEC sp_OAMethod @wrapper, 'GetAttachedEmail', @success OUT, @i, @nested
        IF @success <> 1
          BEGIN
            EXEC sp_OAGetProperty @wrapper, 'LastErrorText', @sTmp0 OUT
            PRINT @sTmp0
            EXEC @hr = sp_OADestroy @wrapper
            EXEC @hr = sp_OADestroy @nested
            RETURN
          END

        EXEC sp_OAGetProperty @nested, 'From', @sTmp0 OUT
        PRINT 'Original author: ' + @sTmp0

        EXEC sp_OAGetProperty @nested, 'Subject', @sTmp0 OUT
        PRINT 'Original subject: ' + @sTmp0

        EXEC sp_OAGetProperty @nested, 'NumAttachments', @iTmp0 OUT
        PRINT 'Files on the original: ' + @iTmp0
        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @wrapper
    EXEC @hr = sp_OADestroy @nested


END
GO