Sample code for 30+ languages & platforms
SQL Server

Get an Attached Message as an Email Object

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachedEmail method, which copies the Nth embedded message/rfc822 MIME part into another Email object. The index is zero-based (valid values run from 0 through NumAttachedMessages - 1). This example attaches an email and then extracts it back into its own object.

Background: When a message forwards another email as an attachment, that nested message is a complete email in its own right. GetAttachedEmail turns it back into a fully navigable Email object so you can read its subject, sender, body, and even its own attachments — essential for processing forwarded mail, or for tools that unpack reported spam/phishing to examine the original.

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 GetAttachedEmail method, which copies the Nth embedded message/rfc822
    --  MIME part into another Email object.  The index is zero-based.

    --  Build an inner email and attach it to an outer email.
    DECLARE @innerEmail int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @innerEmail OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OASetProperty @innerEmail, 'Subject', 'Embedded message'
    EXEC sp_OASetProperty @innerEmail, 'From', 'alice@example.com'
    EXEC sp_OASetProperty @innerEmail, 'Body', 'This is the embedded message.'

    DECLARE @email int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email OUT

    EXEC sp_OASetProperty @email, 'Subject', 'Has an attached message'
    EXEC sp_OAMethod @email, 'AttachEmail', @success OUT, @innerEmail
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @innerEmail
        EXEC @hr = sp_OADestroy @email
        RETURN
      END

    --  Copy the first embedded message (index 0) into its own Email object.
    DECLARE @attached int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @attached OUT

    EXEC sp_OAMethod @email, 'GetAttachedEmail', @success OUT, 0, @attached
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @innerEmail
        EXEC @hr = sp_OADestroy @email
        EXEC @hr = sp_OADestroy @attached
        RETURN
      END


    EXEC sp_OAGetProperty @attached, 'Subject', @sTmp0 OUT
    PRINT 'Attached email subject: ' + @sTmp0

    EXEC sp_OAGetProperty @attached, 'From', @sTmp0 OUT
    PRINT 'Attached email from: ' + @sTmp0

    EXEC @hr = sp_OADestroy @innerEmail
    EXEC @hr = sp_OADestroy @email
    EXEC @hr = sp_OADestroy @attached


END
GO