Sample code for 30+ languages & platforms
PureBasic

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

PureBasic
IncludeFile "CkEmail.pb"

Procedure ChilkatExample()

    success.i = 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.

    innerEmail.i = CkEmail::ckCreate()
    If innerEmail.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkEmail::setCkSubject(innerEmail, "Original message")
    CkEmail::setCkFrom(innerEmail, "alice@example.com")
    CkEmail::setCkBody(innerEmail, "This is the original message being forwarded.")

    email.i = CkEmail::ckCreate()
    If email.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkEmail::setCkSubject(email, "FW: Original message")
    CkEmail::setCkFrom(email, "bob@example.com")
    CkEmail::setCkBody(email, "See the attached original email.")

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

    success = CkEmail::ckAttachEmail(email,innerEmail)
    If success = 0
        Debug CkEmail::ckLastErrorText(email)
        CkEmail::ckDispose(innerEmail)
        CkEmail::ckDispose(email)
        ProcedureReturn
    EndIf

    Debug "NumAttachedMessages = " + Str(CkEmail::ckNumAttachedMessages(email))


    CkEmail::ckDispose(innerEmail)
    CkEmail::ckDispose(email)


    ProcedureReturn
EndProcedure