Sample code for 30+ languages & platforms
Zig

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account on an IMAP server.

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 to an IMAP server.
    // Use TLS
    imap.setSsl(true);
    imap.setPort(993);
    imap.connect("imap.example.com") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Login
    imap.login("***", "***") 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;
    };

    // After selecting the mailbox. the total number of emails
    // is immediately available:
    const total_num = imap.getNumMessages();
    std.debug.print("Num messages = {d}\n", .{total_num});

    // To determine the number of unseen messages, a call
    // to Search is required, which returns the set of UIDs
    // of all unseen messages.

    // We can choose to fetch UIDs or sequence numbers.
    const fetch_uids = true;
    const message_set = try chilkat.MessageSet.init();
    defer message_set.deinit();
    imap.queryMbx("UNSEEN", fetch_uids, message_set) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    const num_unseen = @as(u32, @intCast(message_set.getCount()));
    std.debug.print("{d}\n", .{num_unseen});

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

    // Display the UIDs
    var i: i32 = 0;
    while (i < message_set.getCount()) {
        std.debug.print("{d}\n", .{message_set.getId(i)});
        i = i + 1;
    }

    // Disconnect from the IMAP server.
    try imap.disconnect();
}