Sample code for 30+ languages & platforms
SQL Server

Attach an Email to Another Email

See more Email Object Examples

Demonstrates the Chilkat Email.AttachEmail method, which attaches a copy of another email to this email object. The attached email is encapsulated in a message/rfc822 subpart. Because a copy is attached, later changes to the source email do not affect the embedded message. This example attaches one email to another.

Background: "Forward as attachment" produces exactly this structure: the original message is embedded whole as a message/rfc822 part rather than quoted into the body. This preserves the original's headers and formatting intact, which matters for forwarding to a mailbox that will re-parse it, or for reporting spam/phishing with the original evidence attached. Such parts are counted by NumAttachedMessages.

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 AttachEmail method, which attaches a copy of another email to this email
    --  object.  The attached email is encapsulated in a message/rfc822 subpart.

    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', 'Original message'
    EXEC sp_OASetProperty @innerEmail, 'From', 'alice@example.com'
    EXEC sp_OASetProperty @innerEmail, 'Body', 'This is the original message being forwarded.'

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

    EXEC sp_OASetProperty @email, 'Subject', 'FW: Original message'
    EXEC sp_OASetProperty @email, 'From', 'bob@example.com'
    EXEC sp_OASetProperty @email, 'Body', 'See the attached original email.'

    --  Attach a copy of the inner email as a message/rfc822 part.

    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


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

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


END
GO