Sample code for 30+ languages & platforms
Zig

Add a Related Item from a BinData Object

See more Email Object Examples

Demonstrates the Chilkat Email.AddRelatedBd method, which adds a related item (such as an inline image) using the contents of a BinData object, and returns the generated Content-ID. This example loads an image into a BinData, adds it, captures the Content-ID, and references it from the HTML body.

Background: This is the binary, Content-ID-based way to embed an inline resource — the right choice for images, whose bytes belong in a BinData rather than a string. Because Chilkat generates the Content-ID, the usual pattern is: add the item first, capture the returned ID, then build the matching <img src="cid:..."> reference from it (done here with a StringBuilder).

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 AddRelatedBd method, which adds a related item (such as an inline image)
    // using the contents of a BinData object, and returns the generated Content-ID.

    const email = try chilkat.Email.init();
    defer email.deinit();
    email.setSubject("Related image from BinData");

    // Load the image data from a file into a BinData object.
    const bd_image = try chilkat.BinData.init();
    defer bd_image.deinit();
    bd_image.loadFile("qa_data/images/logo.png") catch {
        std.debug.print("{s}\n", .{try bd_image.getLastErrorText(alloc)});
        return;
    };

    // Add the image as a related item; capture its generated Content-ID.
    const cid = email.addRelatedBd(alloc, "logo.png", bd_image) catch {
        std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
        return;
    };

    // Reference the related item in the HTML body by its Content-ID.
    const sb_html = try chilkat.StringBuilder.init();
    defer sb_html.deinit();
    sb_html.append("<html><body><img src=\"cid:PLACEHOLDER_CID\"/></body></html>") catch {};
    _ = sb_html.replace("PLACEHOLDER_CID", cid);
    email.setHtmlBody(try sb_html.getAsString(alloc));

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

    // Note: The path "qa_data/images/logo.png" is a relative local filesystem path,
    // relative to the current working directory of the running application.
}