Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

How to Download Messages in MessageSet One at a Time

See more IMAP Examples

If a message set contains a huge number of emails, it's NOT a good idea to try to download all at once into an email bundle using a method such as FetchBundle. It's better to iterate over the messages in the set to download one by one.

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();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

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

    // Connect using TLS.
    imap.setSsl(true);
    imap.setPort(993);
    imap.connect("imap.example.com") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Authenticate
    imap.login("email_account_login", "email_account_password") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

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

    // Search for messages and return a set of matching messages.
    // (This example will simply search for ALL messages.)
    const fetch_uids = true;

    const message_set = try chilkat.MessageSet.init();
    defer message_set.deinit();
    imap.queryMbx("ALL", fetch_uids, message_set) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Number of messages = {d}\n", .{message_set.getCount()});

    const email = try chilkat.Email.init();
    defer email.deinit();
    var i: i32 = 0;
    while (i < message_set.getCount()) {
        imap.fetchEmail(false, message_set.getId(i), fetch_uids, email) catch {
            std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("{s}; {s}\n", .{ try email.getFrom(alloc), try email.getSubject(alloc) });

        i = i + 1;
    }

    std.debug.print("OK\n", .{});
}