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

IMAP Download All Email One at a Time

Demonstrates how to download every email in an IMAP mailbox one at a time as a MIME string or as an email object. (The MIME contains the full contents of the email including all attachments.)

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

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

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

    // 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("myLogin", "myPassword") 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;
    };

    // Once the mailbox is selected, the NumMessages property
    // will contain the number of messages in the mailbox.
    // You may loop from 1 to NumMessages to
    // fetch each message by sequence number.

    const b_uid = false;
    var mime_str: [:0]const u8 = "";
    var i: i32 = 0;
    const n = imap.getNumMessages();
    i = 1;
    while (i <= n) : (i += 1) {
        // Download the email by sequence number.
        mime_str = try imap.fetchSingleAsMime(alloc, @as(u32, @intCast(i)), b_uid);

        // ... your application may process each MIME string...
    }

    // An alternative is to download each email in the form of an
    // email object, like this:
    const email = try chilkat.Email.init();
    defer email.deinit();
    i = 1;
    while (i <= n) : (i += 1) {
        // Download the email by sequence number.
        try imap.fetchEmail(false, @as(u32, @intCast(i)), b_uid, email);

        // ... your application may process the email object...
    }

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