Sample code for 30+ languages & platforms
Zig

Fetch a MessageSet into an EmailBundle

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchMsgSet method, which downloads the messages identified by a MessageSet and appends them to an EmailBundle. The arguments are headersOnly, the MessageSet, and the EmailBundle (which is not cleared). This example searches for unseen messages and downloads the whole set.

Background: This is the natural pairing with QueryMbx: search to get a MessageSet of matching identifiers, then download exactly those messages in one call. Fetching a set is far more efficient than looping one message at a time, and it returns an EmailBundle you iterate with MessageCount and EmailAt. Pass headersOnly = true to pull just headers for a fast preview list.

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 Imap.FetchMsgSet method, which downloads the messages identified by a
    // MessageSet and appends them to an EmailBundle.  The 1st argument is headersOnly, the 2nd
    // is the MessageSet, and the 3rd is the EmailBundle (which is not cleared).

    const imap = try chilkat.Imap.init();
    defer imap.deinit();

    imap.setSsl(true);
    imap.setPort(993);

    imap.connect("imap.example.com") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    imap.login("user@example.com", "myPassword") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    imap.selectMailbox("Inbox") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Find the messages to download (here, the unseen messages by UID).
    const msg_set = try chilkat.MessageSet.init();
    defer msg_set.deinit();
    imap.queryMbx("UNSEEN", true, msg_set) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Download the messages in the set (full bodies) into a bundle.
    const bundle = try chilkat.EmailBundle.init();
    defer bundle.deinit();
    imap.fetchMsgSet(false, msg_set, bundle) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    const n = bundle.getMessageCount();
    std.debug.print("Fetched {d} messages.\n", .{n});
    const email = try chilkat.Email.init();
    defer email.deinit();
    var i: i32 = 0;
    i = 0;
    while (i < n) : (i += 1) {
        try bundle.emailAt(i, email);
        std.debug.print("{s}\n", .{try email.getSubject(alloc)});
    }

    imap.disconnect() catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };
}