Sample code for 30+ languages & platforms
Zig

Get IMAP Attachment Sizes

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachSize method, which returns the size in bytes of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches headers only and prints each attachment's name and size.

Background: Like the attachment filename, the size comes from ckx-imap-* metadata and is available from a header-only fetch without downloading the body. A client can therefore show attachment sizes in a message preview, and decide whether to auto-download or prompt before pulling a large file.

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.GetMailAttachSize method, which returns the size in bytes of an
    // attachment.  The 1st argument is the Email and the 2nd is the zero-based attachment index.

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

    // Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
    // metadata describing the attachments is present, so the attachment info methods still work.
    const headers_only = true;
    const use_uid = false;
    const seq_num = 1;
    const email = try chilkat.Email.init();
    defer email.deinit();
    imap.fetchEmail(headers_only, @as(u32, @intCast(seq_num)), use_uid, email) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    const num_attach = imap.getMailNumAttach(email);
    var i: i32 = 0;
    i = 0;
    while (i < num_attach) : (i += 1) {
        const fname = imap.getMailAttachFilename(alloc, email, i) catch {
            std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
            return;
        };

        const sz = imap.getMailAttachSize(email, i);
        std.debug.print("{s}: {d} bytes\n", .{ fname, sz });
    }

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