Sample code for 30+ languages & platforms
Zig

Fetch a Single Message's MIME into a StringBuilder

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchSingleAsMimeSb method, which downloads one message's MIME into a StringBuilder. The first argument is the message id, the second (bUid) selects UID vs sequence number, and the third is the StringBuilder, which is cleared first. This example downloads a message by UID and prints the MIME length.

Background: Chilkat interprets the received MIME as UTF-8. Messages using Base64 or quoted-printable transfer encoding are safe because their encoded bytes are ASCII. Raw 8bit or binary content, or unencoded text in a charset such as ISO-8859-1 or Shift_JIS, can be misinterpreted — in those cases use FetchSingleBd to get the exact bytes.

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.FetchSingleAsMimeSb method, which downloads one message's MIME into a
    // StringBuilder.  The 1st argument is the message id, the 2nd (bUid) selects UID vs sequence
    // number, and the 3rd is the StringBuilder (cleared first).

    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 the message ids to download, returning UIDs.
    const want_uids = true;
    const msg_set = try chilkat.MessageSet.init();
    defer msg_set.deinit();
    imap.queryMbx("ALL", want_uids, msg_set) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    if (msg_set.getCount() > 0) {
        const uid = msg_set.getId(0);

        // Download the message's MIME into a StringBuilder.  The id is a UID.
        const use_uid = true;
        const sb_mime = try chilkat.StringBuilder.init();
        defer sb_mime.deinit();
        imap.fetchSingleAsMimeSb(uid, use_uid, sb_mime) catch {
            std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("MIME length: {d} chars\n", .{sb_mime.getLength()});
    }

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