Sample code for 30+ languages & platforms
Unicode C

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 Unicode C Downloads

Unicode C
#include <C_CkEmailW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkEmailW innerEmail;
    HCkEmailW email;

    success = FALSE;

    //  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 = CkEmailW_Create();
    CkEmailW_putSubject(innerEmail,L"Original message");
    CkEmailW_putFrom(innerEmail,L"alice@example.com");
    CkEmailW_putBody(innerEmail,L"This is the original message being forwarded.");

    email = CkEmailW_Create();
    CkEmailW_putSubject(email,L"FW: Original message");
    CkEmailW_putFrom(email,L"bob@example.com");
    CkEmailW_putBody(email,L"See the attached original email.");

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

    success = CkEmailW_AttachEmail(email,innerEmail);
    if (success == FALSE) {
        wprintf(L"%s\n",CkEmailW_lastErrorText(email));
        CkEmailW_Dispose(innerEmail);
        CkEmailW_Dispose(email);
        return true;
    }

    wprintf(L"NumAttachedMessages = %d\n",CkEmailW_getNumAttachedMessages(email));


    CkEmailW_Dispose(innerEmail);
    CkEmailW_Dispose(email);

    }