OfficialEmail

IMAP

Let agents search and read mail and download attachments from an IMAP mailbox. Reading never marks messages as read on Read connections.

  • Draft also lets agents create, update and delete drafts for you to review and send. Updating a draft moves its previous version to Trash.
  • Write also permits flagging, moving and trashing mail, and creating folders. Providers may empty Trash automatically.

This connector never sends email or permanently deletes messages.

Connect your mailbox.

Setup instructions

Connect IMAP

  1. Find your provider's IMAP host and create an app password if required. Houston needs implicit TLS, usually port 993; STARTTLS on 143 is unsupported.
  2. Enter Host, Port, Username (usually your email) and Password.
  3. For Access, choose Read, Draft to manage drafts for you to send, or Write to also organize mail. This connector cannot send email.
  4. Keep TLS mode on Verify certificate and host name (recommended) and select Add connection. For a private server, see Self-signed and private certificates.

Use the dedicated Gmail or Fastmail connector for those services. Outlook.com and Microsoft 365 do not accept the password authentication this connector uses.

Advanced

Self-signed and private certificates

Paste the issuing authority's PEM certificate into CA certificate, including its BEGIN/END CERTIFICATE lines. For a self-signed server, use its own certificate. Never paste a private key. Houston then trusts only that authority.

TLS mode Verification
Verify certificate and host name (recommended) Trusted authority and matching host
Verify certificate only Trusted authority; does not check the host
Encrypted, but doesn't check who the server is Encryption only; use solely for disposable test mailboxes

Without server verification, an interceptor can read your password and mail. An IP host must appear in the certificate's subject alternative names for full verification.

Troubleshooting

Enable IMAP in your provider's settings and use an app password where required. Check the TLS port, certificate chain and host name if the connection fails. Moving messages requires the server's MOVE or UIDPLUS extension.

Files

  • connector.luau
    -- Any mailbox reachable over IMAP, through Houston's TLS connection in the configured TLS
    -- mode; credentials stay on Houston. The native imap.command validates options, encodes
    -- message IDs and decodes MIME, so each operation here forwards one command and documents it.
    type Options = {[string]: any}
    
    local function options(value: any): Options
    	if value == nil then return {} end
    	assert(type(value) == "table", "opts must be an object")
    	for key in value do assert(type(key) == "string", "opts must have named fields") end
    	return table.clone(value)
    end
    
    local function command(name: string, args: Options): any
    	args.command = name
    	return await(imap.command(args))
    end
    
    local exports: {[string]: any} = {}
    local help: {[string]: string} = {}
    
    -- Write connections expose every operation; Draft ones add only drafts to the reads.
    local WRITES = houston.allows("data:write")
    local DRAFTS = houston.allows("data:draft")
    
    help.listMailFolders = "listMailFolders() -> {{id, name, parentId?, role?, totalEmails?, unreadEmails?}} sorted by id. id is the full folder name, such as 'INBOX' or 'Archive/2026'; role is inbox, sent, drafts, trash, junk, archive or all. Some servers list containers that hold no messages: use them as parents, not to search. Counts appear when the server reports them in its folder list."
    function exports.listMailFolders(...: any): any
    	local input = ...
    	assert(select("#", ...) <= 1 and (input == nil or type(input) == "table" and next(input) == nil), "listMailFolders takes no options")
    	return command("list", {})
    end
    
    help.listMessages = "listMessages({folder?, from?, to?, cc?, subject?, text?, since?, before?, unread?, flagged?, maxResults?, pageToken?}) -> {messages={{id}}, nextPageToken?}. Searches one folder (default INBOX), most recently added first. Text filters match substrings, case-insensitively; text searches headers and body. since and before take YYYY-MM-DD and compare the day the server received the message: since includes that day, before excludes it. unread and flagged filter by state when true or false. maxResults is 1 to 500 (default 100). Pass nextPageToken as pageToken, repeating the same folder and filters, until it is absent. IDs only: read them with getMessages."
    function exports.listMessages(input: any): any
    	return command("search", options(input))
    end
    
    help.getMessages = "getMessages({ids, maxBodyBytes?, bodyFormat?}) -> messages in the order of ids, each {id, folder, flags, date, receivedAt, size, subject, from, to, cc, bcc, replyTo, messageId, inReplyTo, body, bodyTruncated, attachments={{id, filename, mimeType, size, inline, contentId}}}. 1 to 50 IDs, and IDs × maxBodyBytes at most 3.5 MiB; the whole reply, as JSON, must stay under 4 MiB. An attachment's size is as stored on the server, about a third above the file's size for base64. bodyFormat: auto (default) chooses nonblank decoded plain text, then an HTML alternative; text or html selects only that format, preserving whitespace and returning an empty string if missing. Whitespace is ignored only when deciding emptiness. A truncated whitespace prefix is not considered empty. maxBodyBytes caps body (default 32768, at most 1048576; 0 skips bodies for a cheap scan) and bodyTruncated reports a cut. flags are IMAP flags such as \\Seen (read), \\Flagged and \\Answered. Reading never marks a message read."
    function exports.getMessages(input: any): any
    	return command("fetch", options(input))
    end
    
    help.getMessage = "getMessage({id, maxBodyBytes?, bodyFormat?}) -> one message shaped like getMessages."
    function exports.getMessage(input: any): any
    	local args = options(input)
    	local id = args.id
    	assert(type(id) == "string" and id ~= "", "id must be a nonempty string")
    	assert(args.ids == nil, "getMessage takes one id; use getMessages for several")
    	args.id, args.ids = nil, {id}
    	return command("fetch", args)[1]
    end
    
    help.getAttachment = "getAttachment({messageId, attachmentId, path}) -> {path, url, size, filename?, mimeType}. Saves an attachment (id from a message's attachments) to a session path, decoded; url is a signed Houston download link. Never inline attachment bytes. The download must finish within 20 seconds."
    function exports.getAttachment(input: any): any
    	local saved = command("download", options(input))
    	saved.url = await(fs.signedGetUrl(saved.path))
    	return saved
    end
    
    local WRITE_NOTE = " A failed or interrupted change may already have applied: check with getMessages or listMessages before repeating it."
    
    if WRITES then
    	help.setFlags = "setFlags({ids, add?, remove?}) -> {ids}. Adds and removes flags on 1 to 1000 messages, e.g. add={'\\\\Seen'} marks read, remove={'\\\\Seen'} marks unread, add={'\\\\Flagged'} stars. Keywords such as $Important are allowed when the server accepts them. Fails without changes if an ID no longer exists." .. WRITE_NOTE
    	function exports.setFlags(input: any): any
    		return command("store", options(input))
    	end
    end
    
    if WRITES then
    	help.moveMessages = "moveMessages({ids, folder}) -> {folder, ids?}. Moves 1 to 1000 messages to a folder id or role (trash, archive, junk...). Messages get new IDs in the destination: ids lists them in input order when the server reports them. Fails without changes if an ID no longer exists." .. WRITE_NOTE
    	function exports.moveMessages(input: any): any
    		return command("move", options(input))
    	end
    end
    
    if WRITES then
    	help.trashMessages = "trashMessages({ids}) -> {folder, ids?}. Moves messages to the trash folder, like moveMessages with folder='trash'. Nothing is deleted permanently here, but many providers empty their trash automatically after some days." .. WRITE_NOTE
    	function exports.trashMessages(input: any): any
    		local args = options(input)
    		assert(args.folder == nil, "trashMessages always moves to the trash folder")
    		args.folder = "trash"
    		return command("move", args)
    	end
    end
    
    if WRITES then
    	help.createFolder = "createFolder({name, parent?}) -> {id, name}. Creates name at the top level or inside parent (a folder id or role); name cannot contain the folder separator. Some servers keep every folder inside INBOX: pass parent='INBOX' there."
    	function exports.createFolder(input: any): any
    		return command("create", options(input))
    	end
    end
    
    local DRAFT_FIELDS = {"to", "cc", "bcc", "subject", "html", "from", "replyTo", "inReplyTo", "replyAll"}
    
    -- Copies the public draft fields, sends text as body (text is the search filter in imap.command) and flattens
    -- attachments into the parallel lists imap.command takes. updateDraft passes the draft it replaces as replace.
    local function draft(name: string, input: any, replacing: boolean): any
    	local args = options(input)
    	local id = args.id
    	args.id = nil
    	if replacing then
    		assert(type(id) == "string" and id ~= "", "id must be a nonempty string")
    	else
    		assert(id == nil, "createDraft takes no id; use updateDraft to replace a draft")
    	end
    	assert(args.text == nil or type(args.text) == "string", "text must be a string")
    	local out: Options = {replace = id, body = args.text}
    	args.text = nil
    	for _, field in DRAFT_FIELDS do
    		out[field], args[field] = args[field], nil
    	end
    	local files = args.attachments
    	args.attachments = nil
    	for key in args do error(name .. " has no " .. key .. " option") end
    	if files ~= nil then
    		local count = 0
    		for key in (if type(files) == "table" then files else {}) do
    			assert(type(key) == "number", "attachments must be a list of paths or {path, filename?, mimeType?}")
    			count += 1
    		end
    		assert(type(files) == "table" and count == #files, "attachments must be a list of paths or {path, filename?, mimeType?}")
    		local paths: {string}, names: {string}, kinds: {string} = json.decode("[]"), json.decode("[]"), json.decode("[]")
    		for _, item in files do
    			local file = if type(item) == "string" then {path = item} else item
    			assert(type(file) == "table" and type(file.path) == "string", "each attachment needs a path")
    			for key in file do
    				assert(key == "path" or key == "filename" or key == "mimeType", "attachments take path, filename and mimeType")
    			end
    			table.insert(paths, file.path)
    			table.insert(names, file.filename or "")
    			table.insert(kinds, file.mimeType or "")
    		end
    		out.attachmentPaths, out.attachmentNames, out.attachmentTypes = paths, names, kinds
    	end
    	return command("draft", out)
    end
    
    local DRAFT_NOTE = "to, cc, bcc and replyTo take an address ('Ana <[email protected]>') or an array of them; from defaults to the account's address when its username is one. text and/or html give the body. inReplyTo=<id from listMessages or getMessages, not its messageId> makes a reply: to, subject (Re:) and threading headers default from the original; replyAll=true also copies its To and Cc (except you) into cc. attachments={'path' or {path, filename?, mimeType?}} reads session files, at most 20 files and 6 MiB in all, and must finish within 20 seconds. Saved with the \\Draft and \\Seen flags; nothing is ever sent. id is absent when the server can't report it."
    
    if DRAFTS then
    	help.createDraft = "createDraft({to?, subject?, text?, html?, cc?, bcc?, replyTo?, from?, attachments?, inReplyTo?, replyAll?}) -> {id?, folder, messageId}. Saves a new draft in the drafts folder for the user to review and send. " .. DRAFT_NOTE .. WRITE_NOTE
    	function exports.createDraft(input: any): any
    		return draft("createDraft", input, false)
    	end
    end
    
    if DRAFTS then
    	help.updateDraft = "updateDraft({id, ...createDraft fields}) -> {id?, folder, messageId}. Replaces a draft (a message flagged \\Draft or in the drafts folder) with a new version built from the given fields, so pass every field to keep. It stays in its conversation (In-Reply-To and References are kept) and keeps its subject when none is given; inReplyTo moves it into that message's conversation instead. Saves the new version in the drafts folder first, then moves the old one to the trash. The draft gets a new id; fields work as in createDraft." .. WRITE_NOTE
    	function exports.updateDraft(input: any): any
    		return draft("updateDraft", input, true)
    	end
    end
    
    if DRAFTS then
    	help.deleteDraft = "deleteDraft({id}) -> {folder, ids?}. Moves a draft to the trash folder, and fails without changes unless the message is flagged \\Draft or in the drafts folder." .. WRITE_NOTE
    	function exports.deleteDraft(input: any): any
    		local args = options(input)
    		local id = args.id
    		args.id = nil
    		assert(type(id) == "string" and id ~= "" and next(args) == nil, "deleteDraft takes one id and nothing else")
    		return command("discard", {ids = {id}})
    	end
    end
    
    function exports.help(): string
    	local names: {string} = {}
    	for name in help do table.insert(names, name) end
    	table.sort(names)
    	local lines = {
    		"IMAP mailbox of the connected account. Operations take one named options object and return plain data; Read connections expose only the reads, and Draft connections add only the draft operations.",
    		"Message IDs are opaque strings tied to their folder: keep them as returned. They change when a message moves, and IDs from before a server reset fail clearly instead of matching another message.",
    		"Folders are folder ids from listMailFolders or roles (inbox, sent, drafts, trash, junk, archive, all); an exact folder name wins over a role.",
    		"Each call opens one connection to the mail server: call sequentially rather than in parallel. Errors carry the server's message. Nothing here sends mail: drafts are saved for the user to review and send.",
    		"Example: local page = listMessages({unread=true, maxResults=20}); local ids = {}; for _, m in page.messages do table.insert(ids, m.id) end; getMessages({ids=ids, maxBodyBytes=0}).",
    	}
    	for _, name in names do table.insert(lines, help[name]) end
    	return table.concat(lines, "\n")
    end
    
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "IMAP",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "description": "Draft lets agents create, update and delete drafts for you to review and send, without changing any other mail. This connector never sends email.",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "draft",
              "label": "Draft"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "config": {
        "host": {
          "label": "IMAP server",
          "order": 2,
          "required": true,
          "type": "string"
        },
        "port": {
          "default": 993,
          "label": "Port",
          "maximum": 65535,
          "minimum": 1,
          "order": 3,
          "type": "integer"
        },
        "username": {
          "label": "Username",
          "order": 4,
          "required": true,
          "type": "string"
        },
        "password": {
          "label": "Password or app password",
          "order": 5,
          "required": true,
          "type": "secret"
        },
        "tls_mode": {
          "default": "verify-full",
          "description": "How Houston checks who the server is. Every mode encrypts the connection. Use the recommended mode for production data.",
          "label": "TLS mode",
          "options": [
            {
              "label": "Verify certificate and host name (recommended)",
              "value": "verify-full"
            },
            {
              "label": "Verify certificate only: doesn't check the host name",
              "value": "verify-ca"
            },
            {
              "label": "Encrypted, but doesn't check who the server is",
              "value": "require"
            }
          ],
          "order": 6,
          "required": true,
          "type": "string"
        },
        "ca_certificate": {
          "description": "The PEM certificate of the authority that signed your server's certificate, or the server's own self-signed certificate. Required with “Verify certificate only”. With the recommended mode, Houston then trusts only this authority instead of public ones.",
          "format": "pem",
          "label": "CA certificate",
          "max_length": 65536,
          "multiline": true,
          "order": 7,
          "placeholder": "-----BEGIN CERTIFICATE-----",
          "type": "string"
        }
      },
      "proxy": [
        {
          "match": {
            "protocol": "imap"
          },
          "action": {
            "connection": {
              "host": "{{config.host}}",
              "port": "{{config.port}}",
              "user": "{{config.username}}",
              "password": "{{config.password}}",
              "tls": {
                "mode": "{{config.tls_mode}}",
                "ca": "{{config.ca_certificate}}"
              }
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Give agents access to any IMAP mailbox to find, read, and organize email and prepare drafts, read-only unless you allow changes.
    ---
    
    # IMAP
    
    Let agents search and read mail and download attachments from an IMAP mailbox.
    Reading never marks messages as read on **Read** connections.
    
    - **Draft** also lets agents create, update and delete drafts for you to
      review and send. Updating a draft moves its previous version to Trash.
    - **Write** also permits flagging, moving and trashing mail, and creating
      folders. Providers may empty Trash automatically.
    
    > This connector never sends email or permanently deletes messages.
    
    [Connect your mailbox](SETUP.md).
    
  • SETUP.md
    # Connect IMAP
    
    1. Find your provider's IMAP host and create an app password if required.
       Houston needs implicit TLS, usually port **993**; STARTTLS on 143 is unsupported.
    2. Enter **Host**, **Port**, **Username** (usually your email) and **Password**.
    3. For **Access**, choose **Read**, **Draft** to manage drafts for you to send, or
       **Write** to also organize mail. This connector cannot send email.
    4. Keep **TLS mode** on **Verify certificate and host name (recommended)** and
       select **Add connection**. For a private server, see
       [Self-signed and private certificates](#self-signed-and-private-certificates).
    
    > Use the dedicated Gmail or Fastmail connector for those services. Outlook.com
    > and Microsoft 365 do not accept the password authentication this connector uses.
    
    ## Advanced
    
    ### Self-signed and private certificates
    
    Paste the issuing authority's PEM certificate into **CA certificate**, including
    its BEGIN/END CERTIFICATE lines. For a self-signed server, use its own certificate.
    Never paste a private key. Houston then trusts only that authority.
    
    | TLS mode | Verification |
    | --- | --- |
    | **Verify certificate and host name (recommended)** | Trusted authority and matching host |
    | **Verify certificate only** | Trusted authority; does not check the host |
    | **Encrypted, but doesn't check who the server is** | Encryption only; use solely for disposable test mailboxes |
    
    > Without server verification, an interceptor can read your password and mail.
    > An IP host must appear in the certificate's subject alternative names for full
    > verification.
    
    ### Troubleshooting
    
    Enable IMAP in your provider's settings and use an app password where required.
    Check the TLS port, certificate chain and host name if the connection fails.
    Moving messages requires the server's MOVE or UIDPLUS extension.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {
      					host = "database.example.com",
      					password = "synthetic-root-secret",
      					username = "reader",
      				},
      				method = "",
      				native = true,
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • drafts.luau
      -- Drafts forward one draft or discard command; attachments flatten into parallel lists.
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "imap.example.com", username = "[email protected]", password = "fixture-password"}},
      	access = {data = "write"},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			if request.command == "discard" then return fixture.operation({folder = "Trash", ids = {"9:5:Trash"}}) end
      			return fixture.operation({id = "3:" .. #requests .. ":Drafts", folder = "Drafts", messageId = "[email protected]"})
      		end}
      	end,
      	run = function(c)
      		local saved = c.createDraft({
      			to = "Grace <[email protected]>", cc = {"[email protected]", "[email protected]"}, subject = "Hello", text = "Hi", html = "<p>Hi</p>",
      			attachments = {"files/report.pdf", {path = "files/notes", filename = "notes.txt", mimeType = "text/plain"}},
      		})
      		assert(saved.id == "3:1:Drafts" and saved.folder == "Drafts" and saved.messageId == "[email protected]", json.encode(saved))
      		local first = requests[1]
      		assert(first.command == "draft" and first.to == "Grace <[email protected]>" and first.cc[2] == "[email protected]" and first.html == "<p>Hi</p>" and first.body == "Hi" and first.text == nil)
      		assert(first.attachments == nil and first.replace == nil and first.id == nil)
      		assert(json.encode(first.attachmentPaths) == '["files/report.pdf","files/notes"]', json.encode(first.attachmentPaths))
      		assert(json.encode(first.attachmentNames) == '["","notes.txt"]' and json.encode(first.attachmentTypes) == '["","text/plain"]')
      
      		c.createDraft({inReplyTo = "7:42:INBOX", replyAll = true, text = "Thanks", attachments = {}})
      		assert(requests[2].inReplyTo == "7:42:INBOX" and requests[2].replyAll == true and json.encode(requests[2].attachmentPaths) == "[]")
      		c.createDraft()
      		assert(requests[3].command == "draft" and requests[3].attachmentPaths == nil)
      
      		for _, rejected in {
      			{id = "3:1:Drafts"}, {replace = "3:1:Drafts"}, {attachmentPaths = {"x"}}, {send = true}, {text = 42},
      			{attachments = {path = "files/a", filename = "a.txt"}},
      			{attachments = {{path = "files/a", size = 3}}}, {attachments = {{filename = "a.txt"}}}, {attachments = "files/a"},
      		} do
      			assert(not pcall(c.createDraft, rejected), json.encode(rejected))
      		end
      		assert(#requests == 3, "rejected drafts never reach the server")
      
      		local updated = c.updateDraft({id = "3:1:Drafts", subject = "Hello again", to = "[email protected]"})
      		assert(updated.id == "3:4:Drafts" and requests[4].replace == "3:1:Drafts" and requests[4].id == nil and requests[4].subject == "Hello again")
      		assert(not pcall(c.updateDraft, {subject = "no id"}) and not pcall(c.updateDraft, {id = "3:1:Drafts", replace = "3:2:Drafts"}))
      		assert(#requests == 4, "rejected updates never reach the server")
      
      		local discarded = c.deleteDraft({id = "3:4:Drafts"})
      		assert(requests[5].command == "discard" and #requests[5].ids == 1 and requests[5].ids[1] == "3:4:Drafts")
      		assert(discarded.folder == "Trash" and discarded.ids[1] == "9:5:Trash", json.encode(discarded))
      		assert(not pcall(c.deleteDraft, {id = "3:4:Drafts", folder = "Archive"}) and not pcall(c.deleteDraft, {ids = {"3:4:Drafts"}}))
      		assert(#requests == 5, "rejected deletes never reach the server")
      	end,
      }
      
    • read_draft.luau
      -- Draft connections expose the reads and the draft operations, and no other change.
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "imap.example.com", username = "[email protected]", password = "fixture-password"}},
      	access = {data = "draft"},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			if request.command == "discard" then return fixture.operation({folder = "Trash"}) end
      			return fixture.operation({id = "3:1:Drafts", folder = "Drafts", messageId = "[email protected]"})
      		end}
      	end,
      	run = function(c)
      		local names: {string} = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "createDraft,deleteDraft,getAttachment,getMessage,getMessages,listMailFolders,listMessages,updateDraft", table.concat(names, ","))
      		assert(c.createDraft({to = "[email protected]", text = "Hi"}).id == "3:1:Drafts" and requests[1].command == "draft")
      		assert(c.updateDraft({id = "3:1:Drafts", text = "Hello"}) ~= nil and requests[2].replace == "3:1:Drafts")
      		assert(c.deleteDraft({id = "3:1:Drafts"}).folder == "Trash" and requests[3].command == "discard")
      	end,
      }
      
    • read_only.luau
      -- Read connections expose only reads; each forwards one native command.
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "imap.example.com", username = "[email protected]", password = "fixture-password"}},
      	access = {data = "read"},
      	configure = function()
      		requests, replies = {}, {}
      		fs = fixture.files()
      		imap = {command = function(request)
      			table.insert(requests, request)
      			assert(#replies > 0, "unexpected command " .. tostring(request.command))
      			return fixture.operation(table.remove(replies, 1))
      		end}
      	end,
      	run = function(c)
      		for _, name in {"setFlags", "moveMessages", "trashMessages", "createFolder", "createDraft", "updateDraft", "deleteDraft"} do
      			assert(c[name] == nil, "Read access leaked " .. name)
      		end
      
      		assert(not pcall(c.listMailFolders, "unexpected"))
      		assert(not pcall(c.listMailFolders, {folder = "INBOX"}), "list takes no options")
      		assert(not pcall(c.listMailFolders, {}, "Archive"), "list takes one argument at most")
      		assert(#requests == 0, "rejected calls never reach the server")
      		replies = {json.decode("[]")}
      		assert(json.encode(c.listMailFolders()) == "[]", "empty folders must remain a JSON array")
      		local fields = 0
      		for _ in requests[1] do fields += 1 end
      		assert(requests[1].command == "list" and fields == 1, "list takes no options")
      		replies = {{{id = "INBOX", name = "INBOX", role = "inbox"}, {id = "INBOX/Receipts", name = "Receipts", parentId = "INBOX"}}}
      		local folders = c.listMailFolders({})
      		assert(#folders == 2 and folders[1].role == "inbox" and folders[2].parentId == "INBOX", json.encode(folders))
      		assert(requests[2].command == "list")
      
      		local opts = {folder = "Archive/2026", unread = true, maxResults = 20}
      		replies = {{messages = json.decode("[]")}, {messages = {{id = "7:43:INBOX"}, {id = "7:42:INBOX"}}, nextPageToken = "7:42:INBOX"}}
      		assert(json.encode(c.listMessages(opts).messages) == "[]")
      		local search = requests[3]
      		assert(search.command == "search" and search.folder == "Archive/2026" and search.unread == true and search.maxResults == 20)
      		assert(opts.command == nil, "the caller's options must not change")
      		local page = c.listMessages({unread = true, maxResults = 2, pageToken = "7:44:INBOX"})
      		assert(#page.messages == 2 and page.messages[1].id == "7:43:INBOX" and page.nextPageToken == "7:42:INBOX", json.encode(page))
      		assert(requests[4].command == "search" and requests[4].pageToken == "7:44:INBOX" and requests[4].unread == true)
      
      		replies = {{{id = "7:42:INBOX", subject = "Hello"}}}
      		assert(c.getMessage({id = "7:42:INBOX", maxBodyBytes = 0}).subject == "Hello")
      		local fetch = requests[5]
      		assert(fetch.command == "fetch" and fetch.id == nil and #fetch.ids == 1 and fetch.ids[1] == "7:42:INBOX" and fetch.maxBodyBytes == 0)
      		assert(not pcall(c.getMessage, {}), "id is required")
      		assert(not pcall(c.getMessage, {id = "7:42:INBOX", ids = {"7:43:INBOX"}}), "getMessage takes one id")
      		assert(not pcall(c.listMessages, "INBOX"), "options must be a table")
      		assert(#requests == 5, "rejected calls never reach the server")
      
      		replies = {{path = "files/report.pdf", size = 3, mimeType = "application/pdf", filename = "report.pdf"}}
      		local saved = c.getAttachment({messageId = "7:42:INBOX", attachmentId = "2", path = "files/report.pdf"})
      		local download = requests[6]
      		assert(download.command == "download" and download.messageId == "7:42:INBOX" and download.attachmentId == "2" and download.path == "files/report.pdf")
      		assert(saved.path == "files/report.pdf" and saved.url == "https://houston.test/files/report.pdf" and saved.size == 3, json.encode(saved))
      
      		replies = {{{id = "7:42:INBOX", body = "<p>Hello</p>"}}, {{id = "7:42:INBOX", body = "Hello"}}}
      		assert(c.getMessage({id = "7:42:INBOX", bodyFormat = "html"}).body == "<p>Hello</p>")
      		assert(requests[7].bodyFormat == "html" and requests[7].command == "fetch")
      		assert(c.getMessages({ids = {"7:42:INBOX"}, bodyFormat = "text"})[1].body == "Hello")
      		assert(requests[8].bodyFormat == "text" and requests[8].ids[1] == "7:42:INBOX")
      		assert(#requests == 8)
      	end,
      }
      
    • read_write.luau
      -- Write connections add the changes; trash is a move to the trash role.
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "imap.example.com", port = 1993, username = "[email protected]", password = "fixture-password"}},
      	access = {data = "write"},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			if request.command == "store" then return fixture.operation({ids = request.ids}) end
      			if request.command == "create" then return fixture.operation({id = request.parent .. "/" .. request.name, name = request.name}) end
      			local moved: {string} = json.decode("[]")
      			for i in request.ids do table.insert(moved, "9:" .. (100 + i) .. ":" .. request.folder) end
      			return fixture.operation({folder = request.folder, ids = moved})
      		end}
      	end,
      	run = function(c)
      		local ids = {"7:42:INBOX", "7:43:INBOX"}
      		local flagged = c.setFlags({ids = ids, add = {"\\Seen"}})
      		assert(requests[1].command == "store" and requests[1].add[1] == "\\Seen" and #requests[1].ids == 2 and requests[1].ids[2] == "7:43:INBOX")
      		assert(#flagged.ids == 2 and flagged.ids[2] == "7:43:INBOX", json.encode(flagged))
      
      		local moved = c.moveMessages({ids = ids, folder = "archive"})
      		assert(requests[2].command == "move" and requests[2].folder == "archive")
      		assert(moved.folder == "archive" and #moved.ids == 2 and moved.ids[1] == "9:101:archive", json.encode(moved))
      
      		local trashed = c.trashMessages({ids = {"7:42:INBOX"}})
      		assert(requests[3].command == "move" and requests[3].folder == "trash")
      		assert(trashed.folder == "trash" and #trashed.ids == 1 and trashed.ids[1] == "9:101:trash", json.encode(trashed))
      		assert(not pcall(c.trashMessages, {ids = {"7:42:INBOX"}, folder = "Archive"}), "trash cannot target another folder")
      		assert(#requests == 3, "rejected calls never reach the server")
      
      		local folder = c.createFolder({name = "Receipts", parent = "INBOX"})
      		assert(requests[4].command == "create" and requests[4].parent == "INBOX" and requests[4].name == "Receipts")
      		assert(folder.id == "INBOX/Receipts" and folder.name == "Receipts", json.encode(folder))
      
      		c.setFlags({ids = {"7:42:INBOX"}, remove = {"\\Seen"}})
      		assert(requests[5].remove[1] == "\\Seen" and requests[5].ids[1] == "7:42:INBOX" and requests[5].add == nil)
      		assert(#requests == 5)
      	end,
      }
      
    • tls_bad_ca.luau
      -- A CA certificate that isn't PEM is rejected when the connection is set up.
      return {
      	scenario = {
      		publisher = {}, auth_method = "", auth_config = {},
      		config = {host = "203.0.113.7", username = "[email protected]", password = "fixture-password", tls_mode = "verify-ca", ca_certificate = "MIIBizCCATGgAwIBAgIU"},
      		settings_error = "config.ca_certificate: must be PEM certificates",
      	},
      }
      
    • tls_private_ca.luau
      -- TLS mode verify-full with a CA certificate checks the host name against a private authority.
      local CA = [[-----BEGIN CERTIFICATE-----
      MIIBizCCATGgAwIBAgIUUZi7NGCxGbSs3OHB4dQS1a9pUi0wCgYIKoZIzj0EAwIw
      GjEYMBYGA1UEAwwPRXhhbXBsZSBEZW1vIENBMCAXDTI2MTEwMzA2MDY0MFoYDzIx
      MjYxMDEwMDYwNjQwWjAaMRgwFgYDVQQDDA9FeGFtcGxlIERlbW8gQ0EwWTATBgcq
      hkjOPQIBBggqhkjOPQMBBwNCAATI/yE1WYWuNPmmIUj261YB2ev1y5LpGyLo/gaN
      a29K66kUvWKNSDZsHkDrrEXHNHpYPk5h4QP8G8hMP/4BZIEuo1MwUTAdBgNVHQ4E
      FgQU5s3Uplu6j/FgCEkbvbrWWgHDF8MwHwYDVR0jBBgwFoAU5s3Uplu6j/FgCEkb
      vbrWWgHDF8MwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBj6IfJ
      VlQ/taNheI/sn4McmVv1/0P924pHrGmKDe0/8QIhAKbtQpz1q8WUpaglTkdSdvXx
      Q89QH7BqdNjwVmDoqTu8
      -----END CERTIFICATE-----
      ]]
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "mail.internal.example.com", username = "[email protected]", password = "fixture-password", tls_mode = "verify-full", ca_certificate = CA}},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			return fixture.operation(json.decode("[]"))
      		end}
      	end,
      	run = function(c)
      		assert(json.encode(c.listMailFolders()) == "[]" and #requests == 1 and requests[1].command == "list")
      	end,
      }
      
    • tls_require.luau
      -- TLS mode require encrypts without checking the certificate, so it needs no CA certificate.
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "imap.example.com", username = "[email protected]", password = "fixture-password", tls_mode = "require"}},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			return fixture.operation(json.decode("[]"))
      		end}
      	end,
      	run = function(c)
      		assert(json.encode(c.listMailFolders()) == "[]" and #requests == 1 and requests[1].command == "list")
      	end,
      }
      
    • tls_verify_ca.luau
      -- TLS mode verify-ca trusts only the pasted CA certificate and skips the host name check.
      local CA = [[-----BEGIN CERTIFICATE-----
      MIIBizCCATGgAwIBAgIUUZi7NGCxGbSs3OHB4dQS1a9pUi0wCgYIKoZIzj0EAwIw
      GjEYMBYGA1UEAwwPRXhhbXBsZSBEZW1vIENBMCAXDTI2MTEwMzA2MDY0MFoYDzIx
      MjYxMDEwMDYwNjQwWjAaMRgwFgYDVQQDDA9FeGFtcGxlIERlbW8gQ0EwWTATBgcq
      hkjOPQIBBggqhkjOPQMBBwNCAATI/yE1WYWuNPmmIUj261YB2ev1y5LpGyLo/gaN
      a29K66kUvWKNSDZsHkDrrEXHNHpYPk5h4QP8G8hMP/4BZIEuo1MwUTAdBgNVHQ4E
      FgQU5s3Uplu6j/FgCEkbvbrWWgHDF8MwHwYDVR0jBBgwFoAU5s3Uplu6j/FgCEkb
      vbrWWgHDF8MwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBj6IfJ
      VlQ/taNheI/sn4McmVv1/0P924pHrGmKDe0/8QIhAKbtQpz1q8WUpaglTkdSdvXx
      Q89QH7BqdNjwVmDoqTu8
      -----END CERTIFICATE-----
      ]]
      return {
      	scenario = {publisher = {}, auth_method = "", auth_config = {}, config = {host = "203.0.113.7", username = "[email protected]", password = "fixture-password", tls_mode = "verify-ca", ca_certificate = CA}},
      	configure = function()
      		requests = {}
      		imap = {command = function(request)
      			table.insert(requests, request)
      			return fixture.operation(json.decode("[]"))
      		end}
      	end,
      	run = function(c)
      		assert(json.encode(c.listMailFolders()) == "[]" and #requests == 1 and requests[1].command == "list")
      	end,
      }