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

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

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 assumes 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);
    // Use your IMAP server domain.  This example
    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;
    };

    // Get message ID's for emails older than 1/1/2025
    const fetch_uids = true;
    const message_set = try chilkat.MessageSet.init();
    defer message_set.deinit();
    imap.queryMbx("SENTBEFORE 01-Jan-2025", fetch_uids, message_set) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // If desired, we can examine the Subject of each email to be deleted..
    const email = try chilkat.Email.init();
    defer email.deinit();
    var i: i32 = 0;
    const count = message_set.getCount();
    const header_only = true;

    while (i < count) {
        imap.fetchEmail(header_only, message_set.getId(i), true, email) catch {
            std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("{s}\n", .{try email.getLocalDateStr(alloc)});
        std.debug.print("{s}\n", .{try email.getSubject(alloc)});

        i = i + 1;
    }

    // Set the Deleted flag for each message:
    imap.setFlags(message_set, "Deleted", 1) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Expunge and close the mailbox.
    imap.expungeAndClose() catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

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