Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const inner_email = try chilkat.Email.init();
    defer inner_email.deinit();
    inner_email.setSubject("Original message");
    inner_email.setFrom("alice@example.com");
    inner_email.setBody("This is the original message being forwarded.");

    const email = try chilkat.Email.init();
    defer email.deinit();
    email.setSubject("FW: Original message");
    email.setFrom("bob@example.com");
    email.setBody("See the attached original email.");

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

    email.attachEmail(inner_email) catch {
        std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("NumAttachedMessages = {d}\n", .{email.getNumAttachedMessages()});
}