Sample code for 30+ languages & platforms
DataFlex

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 DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Variant vInnerEmail
    Handle hoInnerEmail
    Handle hoEmail
    String sTemp1
    Integer iTemp1

    Move False To iSuccess

    //  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.

    Get Create (RefClass(cComChilkatEmail)) To hoInnerEmail
    If (Not(IsComObjectCreated(hoInnerEmail))) Begin
        Send CreateComObject of hoInnerEmail
    End
    Set ComSubject Of hoInnerEmail To "Original message"
    Set ComFrom Of hoInnerEmail To "alice@example.com"
    Set ComBody Of hoInnerEmail To "This is the original message being forwarded."

    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End
    Set ComSubject Of hoEmail To "FW: Original message"
    Set ComFrom Of hoEmail To "bob@example.com"
    Set ComBody Of hoEmail To "See the attached original email."

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

    Get pvComObject of hoInnerEmail to vInnerEmail
    Get ComAttachEmail Of hoEmail vInnerEmail To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoEmail To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComNumAttachedMessages Of hoEmail To iTemp1
    Showln "NumAttachedMessages = " iTemp1


End_Procedure