Sample code for 30+ languages & platforms
Zig

Get IMAP Attachment Filenames

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachFilename method, which returns the filename of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches only the message headers and lists the attachment filenames.

Background: This method reads the filename from ckx-imap-* metadata, so it works on a header-only email even though the attachment bodies have not been downloaded. That is exactly what a mail client needs to render the paperclip list — the names of the attached files — before the user decides to download any of them.

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.GetMailAttachFilename method, which returns the filename 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;
    };

    // Loop over the attachments and print each filename.
    const num_attach = imap.getMailNumAttach(email);
    std.debug.print("Attachments: {d}\n", .{num_attach});
    var i: i32 = 0;
    i = 0;
    while (i < num_attach) : (i += 1) {
        // GetMailAttachFilename returns a string, so assign it to a string variable.
        const fname = imap.getMailAttachFilename(alloc, email, i) catch {
            std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("{s}\n", .{fname});
    }

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