// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Demo CLI for the imap library: connects to a mail server, prints what it //! can do, and — given credentials — lists the mailboxes, opens one, and //! optionally fetches a message. //! //! Usage: //! //! imap [--port N] [--no-tls|--insecure-tls|--starttls] //! [--user NAME] [--allow-cleartext] [--mailbox NAME] //! [--fetch UID] [--headers UID] [--search CRITERIA] //! //! The password is read from the IMAP_PASSWORD environment variable, so that //! it does not sit in the shell history or in `ps` output. const std = @import("std"); const imap = @import("imap"); pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; var args = init.minimal.args.iterate(); _ = args.next(); // program name var host: ?[]const u8 = null; var port: ?u16 = null; var tls_mode: imap.Connection.Options.TlsMode = .on; var use_starttls = false; var username: ?[]const u8 = null; var allow_cleartext = false; var mailbox_name: []const u8 = "INBOX"; var fetch_uid: ?u32 = null; var headers_uid: ?u32 = null; var search: []const u8 = "UNSEEN"; while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--no-tls")) { tls_mode = .off; } else if (std.mem.eql(u8, arg, "--insecure-tls")) { tls_mode = .insecure; } else if (std.mem.eql(u8, arg, "--starttls")) { // Start in the clear on port 143 and upgrade in place. tls_mode = .off; use_starttls = true; } else if (std.mem.eql(u8, arg, "--allow-cleartext")) { allow_cleartext = true; } else if (std.mem.eql(u8, arg, "--port")) { port = try std.fmt.parseUnsigned(u16, args.next() orelse return usage(), 10); } else if (std.mem.eql(u8, arg, "--user")) { username = args.next() orelse return usage(); } else if (std.mem.eql(u8, arg, "--mailbox")) { mailbox_name = args.next() orelse return usage(); } else if (std.mem.eql(u8, arg, "--fetch")) { fetch_uid = try std.fmt.parseUnsigned(u32, args.next() orelse return usage(), 10); } else if (std.mem.eql(u8, arg, "--headers")) { headers_uid = try std.fmt.parseUnsigned(u32, args.next() orelse return usage(), 10); } else if (std.mem.eql(u8, arg, "--search")) { search = args.next() orelse return usage(); } else if (host == null) { host = arg; } else { return usage(); } } const host_arg = host orelse return usage(); var stdout_buffer: [4096]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer); const stdout = &stdout_writer.interface; defer stdout.flush() catch {}; const conn = try imap.Connection.connect(gpa, io, host_arg, .{ .port = port, .tls = tls_mode, }); defer conn.destroy(); var client = conn.client(); // Without this the library refuses to put the password on an unencrypted // connection, which is the right default and the wrong one for a server // on the other side of a tunnel it cannot see. client.allow_cleartext_auth = allow_cleartext; const greeting = try client.readGreeting(); try stdout.print("greeting: {s}{s}\n", .{ if (greeting.status == .preauth) "(preauthenticated) " else "", greeting.text, }); // Most servers put the capabilities in the greeting; ask if this one // did not. if (!client.capabilities.known) _ = try client.capability(); try printCapabilities(stdout, &client.capabilities); if (use_starttls) { if (!client.capabilities.starttls) std.process.fatal("server does not offer STARTTLS", .{}); try conn.startTls(&client, .{ .host = host_arg }); try stdout.writeAll("STARTTLS: TLS negotiated\n"); // Everything the server said before the handshake could have been // written by an attacker, so it is asked again. _ = try client.capability(); try printCapabilities(stdout, &client.capabilities); } if (greeting.status != .preauth) { const name = username orelse { // Without credentials there is nothing else to do. try client.logout(); return; }; const password = init.environ_map.get("IMAP_PASSWORD") orelse std.process.fatal("set IMAP_PASSWORD to the password for {s}", .{name}); const mechanism = try client.authenticate(name, password); try stdout.print("authenticated: {t}\n", .{mechanism}); } // UTF-8 names, where the server will; modified UTF-7 is decoded // otherwise, so the listing reads the same either way. if (client.capabilities.utf8_accept) _ = try client.enable("UTF8=ACCEPT"); var mailboxes = try client.listAlloc(gpa, "", "*", .{}); defer mailboxes.deinit(gpa); try stdout.writeAll("mailboxes:\n"); for (mailboxes.entries) |entry| { try stdout.print(" {s}", .{entry.name}); if (entry.attributes.len > 0) try stdout.print(" ({s})", .{entry.attributes}); try stdout.writeAll("\n"); } const mailbox = try client.examine(mailbox_name); try stdout.print("{s}: {d} messages", .{ mailbox_name, mailbox.exists }); if (mailbox.unseen) |n| try stdout.print(", first unseen is #{d}", .{n}); if (mailbox.uidvalidity) |v| try stdout.print(", UIDVALIDITY {d}", .{v}); try stdout.writeAll("\n"); const found = try client.searchAlloc(gpa, .uid, search); defer gpa.free(found); try stdout.print("search {s}: {d} messages\n", .{ search, found.len }); for (found, 0..) |uid, i| { if (i >= 20) { try stdout.print(" ... and {d} more\n", .{found.len - i}); break; } try printSummary(gpa, stdout, &client, uid); } if (headers_uid) |uid| { try stdout.print("--- headers of UID {d} ---\n", .{uid}); _ = try client.fetchTo(stdout, .uid, uid, "HEADER", .{}); } if (fetch_uid) |uid| { try stdout.print("--- UID {d} ---\n", .{uid}); // Straight through to stdout rather than into memory: a message can // be as large as the server is willing to store. _ = try client.fetchTo(stdout, .uid, uid, "", .{ .limit = .limited(64 * 1024 * 1024), }); } try client.logout(); } /// One line about a message: its UID, size, flags and subject. fn printSummary(gpa: std.mem.Allocator, w: *std.Io.Writer, client: *imap.Client, uid: u32) !void { var f = try client.fetchAlloc(gpa, .uid, uid, "(FLAGS RFC822.SIZE ENVELOPE)", .limited(64 * 1024)); defer f.deinit(gpa); var flags: []const u8 = ""; var size: u64 = 0; var subject: ?imap.String = null; var items = f.items(); while (try items.next()) |item| { if (item.is("FLAGS")) { flags = item.value.list; } else if (item.is("RFC822.SIZE")) { size = item.value.number() orelse 0; } else if (item.is("ENVELOPE")) { const e = try imap.Envelope.parse(item.value.list); subject = e.subject; } } try w.print(" {d:>7} {d:>9} octets {s:<24} ", .{ uid, size, flags }); if (subject) |s| try s.write(w) else try w.writeAll("(no subject)"); try w.writeAll("\n"); } fn printCapabilities(w: *std.Io.Writer, caps: *const imap.Capabilities) !void { try w.print("capabilities: {s}\n", .{caps.raw.list()}); if (caps.raw.truncated) try w.writeAll(" (and more than would fit)\n"); if (caps.auth.any()) try w.print("auth: {s}\n", .{caps.auth.list()}); } fn usage() noreturn { std.process.fatal( \\usage: imap [--port N] [--no-tls|--insecure-tls|--starttls] \\ [--user NAME] [--allow-cleartext] [--mailbox NAME] \\ [--fetch UID] [--headers UID] [--search CRITERIA] \\ \\The password comes from the IMAP_PASSWORD environment variable. \\Sending it over a connection that is not encrypted takes \\--allow-cleartext, which says you know. , .{}); } test "printCapabilities" { const caps = imap.Capabilities.parse("IMAP4rev2 AUTH=PLAIN AUTH=CRAM-MD5 IDLE"); var buf: [512]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try printCapabilities(&w, &caps); try std.testing.expectEqualStrings( "capabilities: IMAP4rev2 AUTH=PLAIN AUTH=CRAM-MD5 IDLE\nauth: PLAIN CRAM-MD5\n", w.buffered(), ); }