Sample code for 30+ languages & platforms
Zig

Search an IMAP Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryMbx method, which searches the selected mailbox using IMAP search criteria and stores the matching message identifiers in a MessageSet. If bUid is true, the identifiers are UIDs; otherwise they are sequence numbers. This example finds unseen messages and lists their UIDs.

Background: IMAP search runs on the server, so you can find matching messages without downloading them. The criteria string is standard IMAP search syntax — for example UNSEEN, FROM "alice@example.com", SUBJECT "invoice", or SINCE 1-Jan-2026 — and terms can be combined. The result is a MessageSet of identifiers you then fetch, flag, copy, or move. Requesting UIDs (bUid = true) is preferred because UIDs remain valid across sessions.

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.QueryMbx method, which searches the selected mailbox using IMAP
    // search criteria and stores the matching message identifiers in a MessageSet.  If bUid is
    // true, the identifiers are UIDs; otherwise they are sequence numbers.

    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;
    };

    // Search for unseen (unread) messages, returning their UIDs.
    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;
    };

    // Iterate the matching message identifiers.
    const n = msg_set.getCount();
    std.debug.print("Matching messages: {d}\n", .{n});
    var i: i32 = 0;
    i = 0;
    while (i < n) : (i += 1) {
        std.debug.print("UID: {d}\n", .{msg_set.getId(i)});
    }

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