Fastmail
Fastmail
Connect agents to your Fastmail inbox so they can find important conversations, read messages, and help you stay on top of email.
Find what matters
- Find emails by person, topic, date, or folder.
- Read a whole conversation to catch up on the context.
- Download attachments and work with them alongside your other files.
Prepare replies for you
With Draft access, agents can also prepare drafts and replies, with attachments, for you to review and send from Fastmail. Reply drafts open in the original conversation. Agents cannot send or change any other mail.
Keep your inbox moving
With Write access, agents can also:
- Send emails, drafts, or replies to a person or an entire conversation.
- Choose which email address to send from and include attachments.
- Create folders, move messages, archive finished conversations, and clear out mail you no longer need.
- Mark individual messages or batches as read or unread.
Read cannot change your inbox or send mail.
Setup instructions
Setup instructions
Connect Fastmail
-
In Fastmail, open Settings → Privacy & Security → Manage API tokens.
-
Create an API token using the JMAP protocol. MCP and Dynamic DNS tokens are not supported.
-
Enable Email. Also enable Email submission if you want agents to send or reply, and Masked Email if you want to list masked addresses.
-
In Houston, choose Access:
- Read for browsing, searching, and downloading attachments.
- Draft to also create, update, and delete drafts that you review and send yourself in Fastmail. Houston never sends with this level.
- Write to also mark mail read/unread, send drafts, send, reply, create folders, move, archive, or delete mail.
Drafts and other changes need a writable Email token; Email submission is only needed for sending. Leave it off so that even Write can prepare drafts but never send them.
-
Paste the token into JMAP API token and select Add connection.
API tokens require a Fastmail plan above Basic.
Write access permits both moving mail to Trash and permanent deletion. Draft access can permanently delete drafts only.
Files
Files
connector.luau
-- Named options are the preferred interface; positional forms remain compatible. type Id = string | {id: string} type IdList = {string} | {{id: string}} | {Id} type Ids = Id | IdList type BodyOptions = {maxBodyValueBytes: number?, bodyFormat: string?} type MessageOptions = BodyOptions & {id: string} type MessagesOptions = BodyOptions & {ids: IdList} type SearchOptions = { from: (string | {string})?, to: (string | {string})?, subject: (string | {string})?, text: (string | {string})?, alias: (string | {string})?, aliases: {string}?, folder: (string | {string})?, folders: {string}?, after: string?, before: string?, includeSpamTrash: boolean?, maxResults: number?, pageToken: string?, } type Address = {email: string, name: string?} type Upload = string | {path: string, filename: string?, mimeType: string?} type SendOptions = { to: {Address}, text: string, subject: string?, identityId: string?, from: string?, cc: {Address}?, bcc: {Address}?, replyTo: {Address}?, attachments: {Upload}?, } type ReplyOptions = { id: string?, messageId: string?, text: string, all: boolean?, subject: string?, identityId: string?, from: string?, to: {Address}?, cc: {Address}?, bcc: {Address}?, replyTo: {Address}?, attachments: {Upload}?, } type Attachment = {id: string, filename: string?, mimeType: string?, size: number?, inline: boolean, contentId: string?} type Download = {path: string, url: string, size: number?} type DownloadItem = string | {id: string, path: string?} type DownloadOptions = {messageId: string, attachmentId: string?, id: string?, path: string?} type DownloadsOptions = {messageId: string, items: {DownloadItem}} type MoveOptions = {ids: Ids?, id: string?, folder: string} type FolderOptions = {name: string, parent: Id?, parentId: string?} type Message = { id: string, threadId: string, from: string, to: string, cc: string, bcc: string, replyTo: string, subject: string?, date: string?, messageId: string?, body: string, bodyTruncated: boolean?, attachments: {Attachment}, received: {string}, headers: {{name: string, value: string}}?, mailboxIds: {[string]: boolean}?, keywords: {[string]: boolean}?, preview: string?, } type Folder = {id: string, name: string, role: string?, parentId: string?, totalEmails: number?, unreadEmails: number?} type Identity = {id: string, email: string, name: string?} type Alias = { email: string, canSend: boolean, masked: boolean, identityId: string?, name: string?, maskedId: string?, state: string?, description: string?, forDomain: string?, } type MoveResult = {ids: {string}, folderId: string} type SendResult = {id: string, submissionId: string} type DraftResult = {id: string, threadId: string?} -- createDraft and updateDraft options: every field is optional, but createDraft needs text and updateDraft needs id. type DraftOptions = { id: string?, text: string?, subject: string?, identityId: string?, from: string?, to: {Address}?, cc: {Address}?, bcc: {Address}?, replyTo: {Address}?, attachments: {Upload}?, } type SendDraftOptions = {id: string, identityId: string?} -- Fastmail's JMAP transport uses the shared Houston HTTP/error/file plumbing. local SESSION_URL = "https://api.fastmail.com/jmap/session" local BATCH_SIZE = 50 local DEFAULT_BODY_BYTES = 65536 local DEFAULT_PAGE_SIZE = 100 local MAX_PAGE_SIZE = 500 local ERROR_SNIPPET_BYTES = 300 local CORE = "urn:ietf:params:jmap:core" local MAIL = "urn:ietf:params:jmap:mail" local SUBMISSION = "urn:ietf:params:jmap:submission" local MASKED = "https://www.fastmail.com/dev/maskedemail" local REQUIRED: {[string]: string} = { ["Identity/get"] = SUBMISSION, ["EmailSubmission/set"] = SUBMISSION, ["MaskedEmail/get"] = MASKED } local SET_ERROR_FIELDS = { "notCreated", "notUpdated", "notDestroyed" } local SEARCH_FIELDS = { "from", "to", "subject", "text" } local ADDRESS_FIELDS = { "from", "to", "cc", "bcc", "replyTo" } local RECIPIENT_FIELDS = { "to", "cc", "bcc", "replyTo" } local MESSAGE_PROPERTIES = { "id", "threadId", "mailboxIds", "keywords", "from", "to", "cc", "bcc", "replyTo", "subject", "sentAt", "receivedAt", "messageId", "headers", "preview", "textBody", "htmlBody", "attachments", "bodyValues" } local FOLDER_PROPERTIES = { "id", "name", "role", "parentId", "totalEmails", "unreadEmails" } type Session = { accountId: string, apiUrl: string, username: string, name: string, capabilities: {[string]: any}, accountCapabilities: {[string]: any}?, maskedAccountId: string?, downloadUrl: string?, uploadUrl: string?, } -- Execution-local discovery cache: keep only fields used by this connector. local cachedSession: Session? = nil type RequestOptions = {method: string, url: string, operation: string, body: string?} type Invocation = {name: string, args: {[string]: any}?} type IdentityOptions = {identityId: string?, from: string?} type UploadOptions = {path: string, mimeType: string, operation: string} -- A sender without an id comes from a draft-only token and cannot submit. type Sender = {id: string?, email: string, name: string?} type Fields = { to: {Address}?, cc: {Address}?, bcc: {Address}?, replyTo: {Address}?, subject: string, text: string?, attachments: {Upload}?, inReplyTo: {string}?, references: {string}?, } type Composed = {sender: Sender, fields: Fields, folders: {any}} type EmailFields = { mailboxIds: {[string]: boolean}, keywords: {[string]: boolean}, from: {Address}?, to: {Address}?, cc: {Address}?, bcc: {Address}?, replyTo: {Address}?, subject: string?, text: string?, html: string?, inReplyTo: {string}?, references: {string}?, attachments: any, } local function fail(operation: string, message: string): never error(json.encode({ connector = "fastmail", operation = operation, layer = "upstream", message = message, retryable = false })) end local function snippet(body: any) if type(body) ~= "string" or body == "" then return "" end -- Bound the copy before normalizing a potentially large error response. return (string.gsub(string.sub(body, 1, ERROR_SNIPPET_BYTES), "%s+", " ")) end local function upstream(operation: string, response: HttpResponse) local status = response.statusCode local body = await(response.body:readPrefix(ERROR_SNIPPET_BYTES)) houston.fail({ operation = operation, layer = "upstream", upstream_status = status, retryable = status == 429 or status == 502 or status == 503 or status == 504, message = "upstream HTTP " .. tostring(status) .. " " .. snippet(body), }) end local function request(options: RequestOptions): any local response = await(http.request({ method = options.method, url = options.url, body = options.body, headers = { ["Content-Type"] = { "application/json" } }, })) if response.statusCode < 200 or response.statusCode >= 300 then upstream(options.operation, response) end local body = await(response.body:readAll()) local ok, decoded = pcall(json.decode, body) if not ok then houston.fail({ operation = options.operation, layer = "upstream", upstream_status = response.statusCode, retryable = false, message = "upstream returned invalid JSON: " .. snippet(body), }) end return decoded end local function session(): Session if cachedSession then return cachedSession end local s = request({method = "GET", url = SESSION_URL, operation = "getProfile"}) local account = type(s) == "table" and type(s.primaryAccounts) == "table" and (s.primaryAccounts :: {[string]: string})[MAIL] if type(account) ~= "string" or account == "" or type(s.apiUrl) ~= "string" or type(s.accounts) ~= "table" or type((s.accounts :: {[string]: any})[account]) ~= "table" then return fail("getProfile", "Fastmail session has no primary mail account; check the token's Email scope") end local maskedAccount = s.primaryAccounts[MASKED] local primaryAccount = (s.accounts :: {[string]: any})[account] local discovered: Session = { accountId = account, apiUrl = s.apiUrl, username = s.username, name = primaryAccount.name, capabilities = if type(s.capabilities) == "table" then (s.capabilities :: {[string]: any}) else {}, accountCapabilities = if type(primaryAccount.accountCapabilities) == "table" then primaryAccount.accountCapabilities else nil, maskedAccountId = if type(maskedAccount) == "string" and maskedAccount ~= "" then maskedAccount else nil, downloadUrl = s.downloadUrl, uploadUrl = s.uploadUrl, } cachedSession = discovered return discovered end -- Session capabilities are what the server supports; account capabilities are what this token may use (RFC 8620). -- Masked Email lives in its own account, so only the session lists it for the mail account. local function has_cap(s: Session, cap: string): boolean if s.capabilities[cap] == nil then return false end local account = if cap == MASKED then nil else s.accountCapabilities return account == nil or account[cap] ~= nil end local function require_cap(s: Session, cap: string, operation: string) if not has_cap(s, cap) then fail(operation, "Fastmail token needs " .. (if cap == SUBMISSION then "Email submission" else "Masked Email") .. " scope") end end -- Sends method calls in one JMAP request and returns their results in order. Calls must not depend on -- each other's results; any error or set failure in the request fails the whole operation. local function call_many(invocations: {Invocation}, operation: string): {any} local s = session() local using = { CORE, MAIL } local methodCalls: {any} = {} for index, item in invocations do local cap = REQUIRED[item.name] if cap then require_cap(s, cap, operation) if not table.find(using, cap) then using[#using + 1] = cap end end local args: {[string]: any} = table.clone(item.args or {}) if args.accountId == nil then args.accountId = s.accountId end local methodCall: {any} = { item.name, args, tostring(index - 1) } methodCalls[index] = methodCall end local response = request({method = "POST", url = s.apiUrl, operation = operation, body = json.encode({ using = using, methodCalls = methodCalls, })}) local responses = type(response) == "table" and response.methodResponses if type(responses) ~= "table" then fail(operation, "Invalid JMAP response") end local results: {any} = {} local function set_problem(data: any): string? for _, field in SET_ERROR_FIELDS do if type(data[field]) == "table" then for id, problem in data[field] do if type(problem) ~= "table" then fail(operation, "Invalid JMAP set error") end return tostring(id) .. ": " .. tostring(problem.type) .. ": " .. tostring(problem.description or "JMAP operation failed") end end end return nil end -- An implicit follow-up, such as the Email/set from onSuccessUpdateEmail, runs only after its call succeeded. local followUp: string? = nil for _, invocation in responses :: {any} do if type(invocation) ~= "table" or type(invocation[2]) ~= "table" then fail(operation, "Invalid JMAP response") end local data = invocation[2] if invocation[1] == "error" then fail(operation, tostring(data.type) .. ": " .. tostring(data.description or "JMAP request failed")) end if type(data.notFound) == "table" and #data.notFound > 0 then fail(operation, "Not found: " .. table.concat(data.notFound, ", ")) end -- Implicit responses share their call's tag and follow its own response. local index = (tonumber(invocation[3]) or -1) + 1 local expected = invocations[index] local primary = expected ~= nil and results[index] == nil and invocation[1] == expected.name local problem = set_problem(data) if problem and primary then fail(operation, problem) end followUp = followUp or problem if primary then results[index] = data end end for index in invocations do if results[index] == nil then fail(operation, "Unexpected JMAP method response") end end if followUp then fail(operation, operation .. " completed, but its automatic follow-up update failed (" .. followUp .. "). The change, such as a sent message, has already happened: do not retry.") end return results end local function call(name: string, arguments: {[string]: any}?, operationName: string?): any return call_many({ { name = name, args = arguments } }, operationName or name)[1] end local function id_of(value: any): string if type(value) == "table" then value = value.id end if type(value) ~= "string" or value == "" then error("fastmail requires a nonempty id") end return value end local function id_list(value: any, operation: string): {string} if type(value) == "string" or (type(value) == "table" and type(value.id) == "string" and value[1] == nil) then value = { value } end if type(value) ~= "table" or #value < 1 then error("fastmail." .. operation .. " requires an id or a list of ids") end local out = {} for _, item in value do out[#out + 1] = id_of(item) end return out end local function as_list(value: any): {any} if type(value) ~= "table" then return json.decode("[]") end return value end local function each_chunk(ids: {string}): () -> {string}? local position = 1 return function(): {string}? if position > #ids then return nil end local last = math.min(position + BATCH_SIZE - 1, #ids) local batch = table.move(ids, position, last, 1, {}) position = last + 1 return batch end end local functions = {} local operationHelp: {[string]: string} = {} operationHelp.getProfile = [==[getProfile() -> {emailAddress, accountId, name, capabilities, canSend}. Reads the connected account profile; does not infer unknown token scopes during discovery.]==] function functions.getProfile() local s = session() local caps: {string} = json.decode("[]") :: {string} if type(s.capabilities) == "table" then for name in (s.capabilities :: {[string]: any}) do -- Match canSend: submission is listed only when this account may use it. if type(name) == "string" and (name ~= SUBMISSION or has_cap(s, SUBMISSION)) then caps[#caps + 1] = name end end end table.sort(caps) return { emailAddress = s.username, accountId = s.accountId, name = s.name, capabilities = caps, canSend = has_cap(s, SUBMISSION), } end operationHelp.listFolders = [==[listFolders() -> {folders={{id,name,role,parentId,totalEmails,unreadEmails}}}. Folder filters accept opaque IDs or roles such as INBOX.]==] function functions.listFolders(): {folders: {Folder}} local data = call("Mailbox/get", { properties = FOLDER_PROPERTIES }) return { folders = as_list(data.list) } end local function folder_id(folders: any, value: any) value = id_of(value) for _, folder in (folders :: {any}) do if folder.id == value then return value end end for _, folder in (folders :: {any}) do if folder.role == string.lower(value) then return folder.id end end error("fastmail: unknown folder " .. value .. "; use listFolders() ids or a role such as INBOX") end local function date(value: any) if type(value) ~= "string" then error("fastmail dates must be YYYY-MM-DD or UTC timestamps") end if string.match(value, "^%d%d%d%d%-%d%d%-%d%d$") then return value .. "T00:00:00Z" end return value end local function query(options: SearchOptions?, threads: boolean): ({string}, string?) local opts: SearchOptions = options or {} local limit = opts.maxResults or DEFAULT_PAGE_SIZE local position = tonumber(opts.pageToken or "0") if type(limit) ~= "number" or limit < 1 or limit > MAX_PAGE_SIZE or limit % 1 ~= 0 then error("fastmail.maxResults must be 1–500") end if not position or position < 0 or position % 1 ~= 0 then error("fastmail.pageToken must be a nonnegative integer") end local filters = {} local function add(key: any, value: any) if value == nil then return end if type(value) == "table" then for _, item in value do add(key, item) end else filters[#filters + 1] = { [key] = value } end end for _, key in SEARCH_FIELDS do add(key, (opts :: any)[key]) end local function add_alias(value: any) if type(value) == "table" then for _, item in value do add_alias(item) end return end if value == nil then return end if type(value) ~= "string" or value == "" then error("fastmail.alias must be an email address") end local conditions: {{[string]: string}} = { { to = value }, { cc = value }, { bcc = value }, { from = value } } filters[#filters + 1] = { operator = "OR", conditions = conditions } end add_alias(opts.alias) add_alias(opts.aliases) if opts.after then add("after", date(opts.after)) end if opts.before then add("before", date(opts.before)) end local needsFolders = opts.folder ~= nil or opts.folders ~= nil or not opts.includeSpamTrash local folders = if needsFolders then functions.listFolders().folders else {} local function add_folder(value: any) if type(value) == "table" then for _, item in value do add_folder(item) end elseif value ~= nil then add("inMailbox", folder_id(folders, value)) end end add_folder(opts.folder) add_folder(opts.folders) if not opts.includeSpamTrash and not opts.folder and not opts.folders then for _, folder in (folders :: {any}) do if folder.role == "junk" or folder.role == "trash" then filters[#filters + 1] = { operator = "NOT", conditions = { { inMailbox = folder.id } } } end end end local filter = nil if #filters > 0 then filter = { operator = "AND", conditions = filters } end local data = call("Email/query", { filter = filter, sort = { { property = "receivedAt", isAscending = false } }, position = position, limit = limit, collapseThreads = threads, calculateTotal = true, }) local nextPage = nil local nextPosition = (data.position or position) + #(data.ids or {}) if #(data.ids or {}) > 0 and ((type(data.total) == "number" and nextPosition < data.total) or (data.total == nil and #data.ids == limit)) then nextPage = tostring(nextPosition) end return data.ids or {}, nextPage end operationHelp.listMessages = [==[listMessages(opts?) -> {messages={{id}},nextPageToken?}. Newest first; loop using nextPageToken until nil, including a possibly empty last page. opts: from,to,subject,text,after,before (date or UTC timestamp),folder/folders,alias/aliases,includeSpamTrash,maxResults (1–500, default 100),pageToken. Alias searches From/To/Cc/Bcc. Array filters combine with AND; spam/trash excluded unless explicitly selected. No Gmail q syntax.]==] function functions.listMessages(opts: SearchOptions?) local ids, nextPage = query(opts, false) local rows: {{id: string}} = json.decode("[]") for _, id in ids do rows[#rows + 1] = { id = id } end return { messages = rows, nextPageToken = nextPage } end local function addresses(values: any) local out = {} for _, value in values or {} do if value.name and value.name ~= "" then out[#out + 1] = value.name .. " <" .. value.email .. ">" else out[#out + 1] = value.email end end return table.concat(out, ", ") end -- JSON null is a truthy sentinel in the sandbox. Remove optional null fields -- before normalizing envelopes and MIME parts; retain it in JMAP set responses. local function remove_nulls(value: any) for key, item in value do if type(item) == "userdata" then value[key] = nil elseif type(item) == "table" then remove_nulls(item) end end end -- Identity/get rows without JSON nulls, as every caller expects. local function identity_list(data: any): {any} local identities = as_list(data.list) for _, item in identities do if type(item) == "table" then remove_nulls(item) end end return identities end local function is_inline(part: any): boolean return part.disposition == "inline" or (part.disposition ~= "attachment" and part.cid ~= nil) end local function attachment_metadata(parts: any): {Attachment} local attachments: {Attachment} = json.decode("[]") for _, part in parts or {} do attachments[#attachments + 1] = { id = part.blobId, filename = part.name, mimeType = part.type, size = part.size, inline = is_inline(part), contentId = part.cid, } end return attachments end -- Match Unicode White_Space, as the native IMAP reader does; preserve the original text. local function hasContent(value: string): boolean for _, point in utf8.codes(value) do if not ((point >= 9 and point <= 13) or point == 32 or point == 0x85 or point == 0xA0 or point == 0x1680 or (point >= 0x2000 and point <= 0x200A) or point == 0x2028 or point == 0x2029 or point == 0x202F or point == 0x205F or point == 0x3000) then return true end end return false end -- Joins the fetched values of body parts of one MIME type (nil: any). local function join_parts(msg: any, parts: any, mimeType: string?): (string, boolean) local out = {} local truncated = false for _, part in parts or {} do local value = msg.bodyValues and msg.bodyValues[part.partId] if value and (mimeType == nil or part.type == nil or part.type == mimeType) then out[#out + 1] = value.value if value.isTruncated then truncated = true end end end return table.concat(out, "\n"), truncated end local function decorate(msg: any, bodyFormat: string): Message remove_nulls(msg) for _, key in ADDRESS_FIELDS do msg[key] = addresses(msg[key]) end msg.date = msg.sentAt or msg.receivedAt msg.messageId = msg.messageId and msg.messageId[1] msg.received = json.decode("[]") for _, header in msg.headers or {} do if string.lower(header.name) == "received" then msg.received[#msg.received + 1] = header.value end end if bodyFormat == "html" then msg.body, msg.bodyTruncated = join_parts(msg, msg.htmlBody, "text/html") else msg.body, msg.bodyTruncated = join_parts(msg, msg.textBody, if bodyFormat == "text" then "text/plain" else nil) end if bodyFormat == "auto" then if not msg.bodyTruncated and not hasContent(msg.body) then msg.body, msg.bodyTruncated = join_parts(msg, msg.htmlBody, nil) end if not msg.bodyTruncated and not hasContent(msg.body) then msg.body = msg.preview or "" end end msg.attachments = attachment_metadata(msg.attachments) msg.bodyValues, msg.textBody, msg.htmlBody = nil, nil, nil return msg end local function body_format(opts: BodyOptions): string local value = if opts.bodyFormat == nil then "auto" else opts.bodyFormat assert(value == "auto" or value == "text" or value == "html", "bodyFormat must be auto, text or html") return value end operationHelp.getMessages = [==[getMessages({ids={...},maxBodyValueBytes:number?,bodyFormat:string?}) -> messages in requested order. Requires 1–50 IDs, each a string or {id}. Positional getMessages(ids,opts?) remains supported. Same fields and body options as getMessage; request fewer messages when responses are too large.]==] function functions.getMessages(input: IdList | MessagesOptions, options: BodyOptions?): {Message} local ids: any = input local opts: BodyOptions = options or {} if type(ids) == "table" and ids.ids then opts, ids = ids, ids.ids end if type(ids) ~= "table" or #ids < 1 or #ids > BATCH_SIZE then error("fastmail.getMessages requires 1–50 ids") end local bodyFormat = body_format(opts) local maxBytes = opts.maxBodyValueBytes or DEFAULT_BODY_BYTES if type(maxBytes) ~= "number" or maxBytes < 0 or maxBytes % 1 ~= 0 then error("fastmail.maxBodyValueBytes must be a nonnegative integer") end local requested = {} for _, id in ids do requested[#requested + 1] = id_of(id) end local data = call("Email/get", { ids = requested, properties = MESSAGE_PROPERTIES, fetchTextBodyValues = bodyFormat ~= "html", fetchHTMLBodyValues = bodyFormat ~= "text", -- Fastmail rejects explicit zero; omitting the argument leaves bodies unlimited. maxBodyValueBytes = if maxBytes > 0 then maxBytes else nil, }) local byId, out = {}, {} for _, msg in data.list or {} do byId[msg.id] = decorate(msg, bodyFormat) end for _, id in requested do if not byId[id] then fail("getMessages", "Missing message " .. id) end out[#out + 1] = byId[id] end return out end local function body_options(value: any, options: BodyOptions?): BodyOptions return options or (if type(value) == "table" then value else {}) end operationHelp.getMessage = [==[getMessage({id:string,maxBodyValueBytes:number?,bodyFormat:string?}) -> message envelope,body,headers,received,attachments. Positional getMessage(id,opts?) remains supported; IDs accept strings or {id}. Envelope includes from,to,cc,bcc,replyTo,subject,date,messageId. bodyFormat: auto (default) chooses the nonblank JMAP text-preferred rendering, then HTML-preferred rendering, then preview (renderings may mix MIME types); text or html selects only that MIME type, preserving whitespace and returning an empty string if missing. Whitespace is ignored only when deciding emptiness. Body parts default 64 KiB; bodyTruncated flags truncation of the selected body. A truncated whitespace prefix is not considered empty. maxBodyValueBytes changes the per-part cap (0 disables it). Request smaller bodies when a proxy response is too large.]==] function functions.getMessage(id: Id | MessageOptions, opts: BodyOptions?): Message local options = body_options(id, opts) return functions.getMessages({ id_of(id) }, options)[1] end operationHelp.listThreads = [==[listThreads(opts?) -> {threads={{id}},nextPageToken?}. Uses the same filters and opaque pagination as listMessages; loop until nextPageToken is nil, even if a page is empty.]==] function functions.listThreads(opts: SearchOptions?) local ids, nextPage = query(opts, true) local threads: {{id: string}} = json.decode("[]") if #ids > 0 then local data = call("Email/get", { ids = ids, properties = { "id", "threadId" } }) local byId = {} for _, msg in data.list or {} do byId[msg.id] = msg.threadId end for _, id in ids do if not byId[id] then fail("listThreads", "Missing message " .. id) end threads[#threads + 1] = { id = byId[id] } end end return { threads = threads, nextPageToken = nextPage } end operationHelp.getThread = [==[getThread({id:string,maxBodyValueBytes:number?,bodyFormat:string?}) -> {id,messages} in conversation order, fetching in batches. Positional getThread(id,opts?) remains supported. Same message-body options as getMessage.]==] function functions.getThread(input: Id | MessageOptions, opts: BodyOptions?): {id: string, messages: {Message}} local options = body_options(input, opts) body_format(options) local id = id_of(input) local data = call("Thread/get", { ids = { id } }) local thread = data.list and data.list[1] if not thread then fail("getThread", "Missing thread " .. id) end local messages: {Message} = json.decode("[]") for batch in each_chunk(thread.emailIds) do for _, msg in functions.getMessages(batch, options) do messages[#messages + 1] = msg end end return { id = id, messages = messages } end operationHelp.listAttachments = [==[listAttachments(messageId) -> attachment metadata {id,filename,mimeType,size,inline,contentId}[]. Attachment bytes are never returned inline.]==] function functions.listAttachments(input: Id | Message): {Attachment} local id: any = input if type(id) == "table" and id.attachments then return id.attachments :: {Attachment} end local requested = id_of(id) local data = call("Email/get", {ids = {requested}, properties = {"id", "attachments"}}, "listAttachments") local msg = data.list and data.list[1] if type(msg) ~= "table" or msg.id ~= requested then fail("listAttachments", "Missing message " .. requested) end remove_nulls(msg) return attachment_metadata(msg.attachments) end operationHelp.getAttachments = [==[getAttachments({messageId:string,items={{id:string,path:string?},...}}) -> ordered {path,url,size}[]. Items also accept ID strings; destination paths must be distinct. Positional getAttachments(messageId,items) remains supported. Streams to session files; never returns inline attachment bytes.]==] function functions.getAttachments(input: Id | DownloadsOptions, requested: {DownloadItem}?): {Download} local messageId: any = input local items: any = requested if type(messageId) == "table" and items == nil then items, messageId = messageId.items or messageId, messageId.messageId end messageId = id_of(messageId) if type(items) ~= "table" then error("fastmail.getAttachments requires attachment items") end if #items == 0 then return json.decode("[]") end local folder = "attachments/" .. url.segment(messageId, "messageId") .. "/" local ids, blobs = {}, {} for index, item in items do ids[index] = id_of(item) blobs[index] = url.segment(ids[index], "blobId") end local s = session() local template = s.downloadUrl if type(template) ~= "string" then return fail("getAttachments", "Missing download URL") end local account = url.segment(s.accountId, "accountId") local byId = {} for _, item in functions.listAttachments(messageId) do byId[item.id] = item end local jobs, paths = {}, {} for index, item in items do local id = ids[index] local attachment = byId[id] if not attachment then error("fastmail: attachment does not belong to this message") end local path = type(item) == "table" and item.path or nil local blob = blobs[index] path = path or (folder .. blob) if paths[path] then error("fastmail: attachment paths must be distinct") end paths[path] = true -- Placeholders are filled by name, wherever the server puts them. IDs must be safe path -- segments; the name only labels the download, so one url.segment refuses becomes a -- plain label. Fastmail puts {type}, which contains a slash, in the query. local ok, name = pcall(url.segment, attachment.filename or "attachment") local values = { accountId = account, blobId = blob, name = if ok then name else "attachment", type = url.encode(if type(attachment.mimeType) == "string" then attachment.mimeType else "application/octet-stream") } local link = string.gsub(template, "{(%w+)}", function(key: any) return values[key] or "" end) jobs[#jobs + 1] = { path = path, size = attachment.size, url = link } end local out = {} for _, job in jobs do local res = await(http.request({ method = "GET", url = job.url })) if res.statusCode < 200 or res.statusCode >= 300 then upstream("getAttachment", res) end local output = fs.open(job.path, "w") output:write(res.body) await(output:close()) out[#out + 1] = { path = job.path, url = await(fs.signedGetUrl(job.path)), size = job.size } end return out end operationHelp.getAttachment = [==[getAttachment({messageId:string,attachmentId:string,path:string?}) -> {path,url,size}. id is also accepted in place of attachmentId. Positional getAttachment(messageId,attachmentId,path?) remains supported. Streams to private session files; url is a signed Houston download. Default path: attachments/<encoded-message-id>/<encoded-attachment-id>. Links expire; files remain scoped to caller and execution workspace.]==] function functions.getAttachment(input: Id | DownloadOptions, attachment: DownloadItem?, destination: string?): Download local messageId: any = input local attachmentId: any = attachment local path = destination if type(messageId) == "table" and attachmentId == nil then path, attachmentId, messageId = messageId.path, messageId.attachmentId or messageId.id, messageId.messageId elseif type(attachmentId) == "table" then path, attachmentId = attachmentId.path or path, attachmentId.id end return functions.getAttachments(messageId, { { id = id_of(attachmentId), path = path } })[1] end operationHelp.listAliases = [==[listAliases() -> {aliases,notes}. Each alias has email,canSend,masked. Sending identities add identityId,name; masked addresses add maskedId,state,description,forDomain. Combines addresses shared by both lists. Missing Email submission or Masked Email scope is explained in notes; fails if neither scope is available.]==] function functions.listAliases(): {aliases: {Alias}, notes: {string}} local s = session() if not has_cap(s, SUBMISSION) and not has_cap(s, MASKED) then fail("listAliases", "Fastmail token needs Email submission and/or Masked Email scope") end local byEmail: {[string]: any} = {} local order: {any} = json.decode("[]") :: {any} local function row(email: string) local key = string.lower(email) local existing = byEmail[key] if existing then return existing end local created = { email = email, canSend = false, masked = false } byEmail[key] = created order[#order + 1] = created return created end local notes: {string} = json.decode("[]") :: {string} if has_cap(s, SUBMISSION) then for _, item in identity_list(call("Identity/get", nil, "listAliases")) do if type(item.email) == "string" and item.email ~= "" then local alias = row(item.email) alias.canSend = true alias.identityId = item.id alias.name = item.name end end else notes[#notes + 1] = "Email submission scope is off, so sending identities were not listed" end if has_cap(s, MASKED) then local account = s.maskedAccountId or s.accountId for _, item in as_list(call("MaskedEmail/get", { accountId = account }, "listAliases").list) do if type(item) == "table" then remove_nulls(item) end if type(item.email) == "string" and item.email ~= "" then local alias = row(item.email) alias.masked = true alias.maskedId = item.id alias.state = item.state alias.description = item.description alias.forDomain = item.forDomain if alias.name == nil and type(item.description) == "string" and item.description ~= "" then alias.name = item.description end end end else notes[#notes + 1] = "Masked Email scope is off, so masked addresses were not listed" end return { aliases = order, notes = notes } end operationHelp.listIdentities = [==[listIdentities() -> {identities}, raw JMAP sending identities. Requires the provider Email submission scope, which may be unknown before the first real call.]==] function functions.listIdentities(): {identities: {Identity}} return { identities = identity_list(call("Identity/get", nil, "listIdentities")) } end local function lower_email(value: any): string? if type(value) ~= "string" or value == "" then return nil end return string.lower(value) end local function pick_identity(identities: {Identity}, options: IdentityOptions): Identity? local identityId, fromEmail = options.identityId, options.from if identityId ~= nil and type(identityId) ~= "string" then error("fastmail identityId must be a string") end if fromEmail ~= nil and type(fromEmail) ~= "string" then error("fastmail from must be an email address") end if identityId then for _, item in identities do if item.id == identityId then return item end end return nil end if fromEmail then local want = lower_email(fromEmail) local domain = want and string.match(want, "(@[^@]+)$") local wildcard: Identity? = nil for _, item in identities do local email = lower_email(item.email) if email == want then return item end -- RFC 8621: an identity such as *@example.com may send from any address at that domain. if wildcard == nil and domain and email == "*" .. domain then wildcard = item end end if wildcard then return { id = wildcard.id, email = fromEmail, name = wildcard.name } end return nil end local username = lower_email(session().username) for _, item in identities do if lower_email(item.email) == username then return item end end if #identities == 1 then return identities[1] end return nil end local function require_identity(identities: {Identity}, options: IdentityOptions): Identity local identityId, fromEmail = options.identityId, options.from local identity = pick_identity(identities, options) if identity then return identity end if type(fromEmail) == "string" then error("fastmail: no sending identity for " .. fromEmail .. "; list aliases with listAliases()") end if type(identityId) == "string" then error("fastmail: no sending identity for " .. identityId .. "; list aliases with listAliases()") end error("fastmail: specify a valid identityId from listIdentities()") end local function upload_blob(options: UploadOptions): any local path, mime, operation = options.path, options.mimeType, options.operation local s = session() local template = s.uploadUrl if type(template) ~= "string" or string.find(template, "{accountId}", 1, true) == nil then return fail(operation, "Fastmail session has no upload URL") end local account = url.segment(s.accountId, "accountId") local endpoint = string.gsub(template, "{accountId}", function() return account end) local stat = await(fs.stat(path)) if not stat.isFile then error("fastmail: attachment path must be a file") end local response = await(http.request({ method = "POST", url = endpoint, body = fs.open(path, "r"), headers = { ["Content-Type"] = { mime } }, })) if response.statusCode < 200 or response.statusCode >= 300 then upstream(operation, response) end local body = await(response.body:readAll()) local ok, decoded = pcall(json.decode, body) if not ok or type(decoded) ~= "table" or type(decoded.blobId) ~= "string" or decoded.blobId == "" then fail(operation, "Fastmail upload did not return a blobId: " .. snippet(body)) end return decoded end local function attachment_parts(items: any, operation: any): any if items == nil then return nil end if type(items) ~= "table" then error("fastmail attachments must be a list of {path}") end local out = {} for _, item in items do local path = item local filename, mime = nil, nil if type(item) == "table" then path = item.path filename = item.filename mime = item.mimeType end if type(path) ~= "string" or path == "" then error("fastmail attachment requires a session file path") end if filename ~= nil and type(filename) ~= "string" then error("fastmail attachment filename must be a string") end if mime ~= nil and (type(mime) ~= "string" or mime == "") then error("fastmail attachment mimeType must be a string") end if filename == nil or filename == "" then filename = string.match(path, "([^/]+)$") or "attachment" end mime = mime or "application/octet-stream" local blob = upload_blob({path = path, mimeType = mime, operation = operation}) local partType = if type(blob.type) == "string" and blob.type ~= "" then blob.type else mime out[#out + 1] = { blobId = blob.blobId, name = filename, type = partType, disposition = "attachment" } end if #out == 0 then return nil end return out end local function nonempty(list: any): any if type(list) == "table" and next(list) == nil then return nil end return list end -- Builds a JMAP Email from structured fields; Fastmail generates the MIME message. local function email_object(email: EmailFields): any local out: {[string]: any} = { mailboxIds = email.mailboxIds, keywords = email.keywords, from = email.from, to = nonempty(email.to), cc = nonempty(email.cc), bcc = nonempty(email.bcc), replyTo = nonempty(email.replyTo), subject = email.subject or "", inReplyTo = email.inReplyTo, references = email.references, attachments = email.attachments, bodyValues = {}, } if email.text ~= nil or email.html == nil then out.textBody = { { partId = "text", type = "text/plain" } } out.bodyValues.text = { value = email.text or "" } end if email.html ~= nil then out.htmlBody = { { partId = "html", type = "text/html" } } out.bodyValues.html = { value = email.html } end return out end local function create_email(operation: string, email: EmailFields): DraftResult local created = call("Email/set", { create = { draft = email_object(email) } }, operation) local made = created.created and created.created.draft if type(made) ~= "table" or type(made.id) ~= "string" or made.id == "" then fail(operation, "Missing draft creation confirmation") end return { id = made.id, threadId = if type(made.threadId) == "string" then made.threadId else nil } end -- Saves a composed message in Drafts; only sending it needs Email submission. local function save_draft(operation: string, message: Composed): DraftResult local drafts = folder_id(message.folders, "drafts") local sender, fields = message.sender, message.fields return create_email(operation, { mailboxIds = { [drafts] = true }, keywords = { ["$draft"] = true, ["$seen"] = true }, from = { { email = sender.email, name = sender.name } }, to = fields.to, cc = fields.cc, bcc = fields.bcc, replyTo = fields.replyTo, subject = fields.subject, text = fields.text, inReplyTo = fields.inReplyTo, references = fields.references, attachments = attachment_parts(fields.attachments, operation), }) end -- No automatic retries: a failed/ambiguous submission leaves the draft in place. local function send_email(operation: string, identity: Sender, emailId: string, folders: {any}): SendResult local drafts, sent = folder_id(folders, "drafts"), folder_id(folders, "sent") assert(identity.id, "sending identity has no id") local submitted = call("EmailSubmission/set", { create = { send = { identityId = identity.id, emailId = emailId } }, -- Patch rather than replace, so a draft's other mailboxes (labels) and keywords (flags) survive sending. onSuccessUpdateEmail = { ["#send"] = { ["mailboxIds/" .. drafts] = json.decode("null"), ["mailboxIds/" .. sent] = true, ["keywords/$draft"] = json.decode("null"), ["keywords/$seen"] = true, } }, }, operation) local submission = submitted.created and submitted.created.send if type(submission) ~= "table" or type(submission.id) ~= "string" or submission.id == "" then fail(operation, "Missing submission confirmation; draft " .. emailId) end return { id = emailId, submissionId = submission.id } end local function submit(operation: string, message: Composed): SendResult folder_id(message.folders, "sent") -- Fail before saving a draft when there is no Sent folder. return send_email(operation, message.sender, save_draft(operation, message).id, message.folders) end -- Sending always verifies its sender against Identity/get, which needs Email submission; -- drafts verify only when the token has that scope. local function verifies(draft: boolean): boolean return not draft or has_cap(session(), SUBMISSION) end -- Reads what composing needs in one request: an optional message, the folders, and the sending identities when verified. local function mail_context(operation: string, verified: boolean, message: Invocation?): ({any}, {Identity}?, any) local reads: {Invocation} = {} if message then reads[1] = message end reads[#reads + 1] = { name = "Mailbox/get", args = { properties = FOLDER_PROPERTIES } } if verified then reads[#reads + 1] = { name = "Identity/get" } end local results = call_many(reads, operation) local base = if message then 1 else 0 local identities = if verified then identity_list(results[base + 2]) else nil return as_list(results[base + 1].list), identities, if message then results[1] else nil end -- Without identities, a draft is from `from` as given, or from the account address. local function sender_of(identities: {Identity}?, body: any): Sender if identities then return require_identity(identities, body) end if body.identityId ~= nil then error("fastmail: identityId needs the Email submission scope; pass from instead") end if body.from ~= nil and (type(body.from) ~= "string" or not string.find(body.from, "@", 1, true)) then error("fastmail from must be an email address") end return { email = body.from or session().username } end local function check_addresses(body: any, operation: string) for _, key in RECIPIENT_FIELDS do if body[key] ~= nil and type(body[key]) ~= "table" then error("fastmail." .. operation .. " " .. key .. " must be an array of { email = ... }") end end end -- Drafts may have no recipients yet; sending requires at least one. local function compose(operation: string, body: any, draft: boolean): Composed if type(body) ~= "table" then error("fastmail." .. operation .. " requires options") end if not draft and (type(body.to) ~= "table" or #body.to == 0) then error("fastmail." .. operation .. " requires to = { { email = ... } }") end check_addresses(body, operation) if type(body.text) ~= "string" then error("fastmail." .. operation .. " requires text") end local verified = verifies(draft) -- An unverified sender needs no request, so a bad one is refused before any. local unverified = if verified then nil else sender_of(nil, body) local folders, identities = mail_context(operation, verified) return { sender = unverified or sender_of(identities, body), folders = folders, fields = { to = body.to, cc = body.cc, bcc = body.bcc, replyTo = body.replyTo, subject = body.subject or "", text = body.text, attachments = body.attachments, } } end local function address_objects(values: any): {Address} local out = {} if type(values) ~= "table" then return out end for _, value in values do if type(value) == "table" and type(value.email) == "string" and value.email ~= "" then local addr = { email = value.email } if type(value.name) == "string" and value.name ~= "" then addr.name = value.name end out[#out + 1] = addr end end return out end local function message_ids(value: any): {string} local out: {string} = json.decode("[]") :: {string} if type(value) == "table" then for _, item in value do if type(item) == "string" and item ~= "" then out[#out + 1] = item end end elseif type(value) == "string" then for token in string.gmatch(value, "%S+") do out[#out + 1] = token end end return out end local function reply_subject(subject: any): string if type(subject) ~= "string" then subject = "" end if string.match(subject, "^[Rr][Ee]:") then return subject end if subject == "" then return "Re:" end return "Re: " .. subject end -- Fastmail adds X-Delivered-To (the address that received the message, often an alias) and X-Resolved-To -- (the account) above the sender's headers. Only the first instance is Fastmail's; later ones may be forged. local DELIVERED_HEADERS = { "header:X-Delivered-To:asAddresses:all", "header:X-Resolved-To:asAddresses:all" } -- Without Identity/get, the account address and the addresses a message was delivered to stand in for -- your sending identities, so a reply comes from the alias that received it and reply-all leaves it out. local function own_addresses(msg: any): {Sender} local own: {Sender} = { { email = session().username } } for _, key in DELIVERED_HEADERS do for _, addr in address_objects(as_list(msg[key])[1]) do own[#own + 1] = { email = addr.email } end end return own end -- Shared by replyMessage and createReplyDraft so both thread and address replies alike. local function compose_reply(operation: string, input: Id | ReplyOptions, options: ReplyOptions?, draft: boolean): Composed local id: any = input local body: any = options if type(id) == "table" and body == nil then body = id id = id.id or id.messageId end id = id_of(id) if type(body) ~= "table" or type(body.text) ~= "string" then error("fastmail." .. operation .. " requires text") end check_addresses(body, operation) local to = address_objects(body.to) if body.to ~= nil and (#to == 0 or #to ~= #body.to) then error("fastmail." .. operation .. " to must be a nonempty array of { email = ... }") end local verified = verifies(draft) local explicit = body.identityId ~= nil or body.from ~= nil -- An unverified sender needs no request, so a bad one is refused before any. local unverified = if explicit and not verified then sender_of(nil, body) else nil local properties = { "id", "messageId", "inReplyTo", "references", "from", "to", "cc", "replyTo", "subject" } if not verified then table.move(DELIVERED_HEADERS, 1, #DELIVERED_HEADERS, #properties + 1, properties) end local folders, identities, data = mail_context(operation, verified, { name = "Email/get", args = { ids = { id }, properties = properties } }) local msg = data.list and data.list[1] if type(msg) ~= "table" then fail(operation, "Missing message " .. id) end remove_nulls(msg) if body.to == nil then local source = msg.replyTo if type(source) ~= "table" or #source == 0 then source = msg.from end to = address_objects(source) if #to == 0 then error("fastmail." .. operation .. ": the message has no reply address") end end local own: {Sender} = identities or own_addresses(msg) local identity: Sender? = nil if explicit then identity = unverified or sender_of(identities, body) else local byEmail: {[string]: any} = {} for _, item in own do local key = lower_email(item.email) if key ~= nil and byEmail[key] == nil then byEmail[key] = item end end for _, list in { msg.to, msg.cc } do for _, addr in address_objects(list) do local key = lower_email(addr.email) if key ~= nil then local hit = byEmail[key] if hit then identity = hit; break end end end if identity then break end end if not identity then identity = require_identity(own :: any, {}) end end assert(identity, "reply identity was not resolved") local cc = body.cc if body.all and cc == nil then -- Leave out your own addresses, including an explicit from that is not one of them. local skip: {[string]: boolean} = {} for _, item in own do local key = lower_email(item.email) if key ~= nil then skip[key] = true end end local sender = lower_email(identity.email) if sender ~= nil then skip[sender] = true end for _, addr in to do local key = lower_email(addr.email) if key ~= nil then skip[key] = true end end local combined = {} local seen: {[string]: boolean} = {} for _, list in { msg.to, msg.cc } do for _, addr in address_objects(list) do local key = lower_email(addr.email) if key ~= nil and not skip[key] and not seen[key] then seen[key] = true combined[#combined + 1] = addr end end end if #combined > 0 then cc = combined end end local ids = message_ids(msg.messageId) local inReplyTo = nil local references = nil if #ids > 0 then inReplyTo = ids local refs: {string} = json.decode("[]") :: {string} local seen: {[string]: boolean} = {} local function add(values: any) for _, value in message_ids(values) do if not seen[value] then seen[value] = true refs[#refs + 1] = value end end end add(msg.references) add(ids) references = refs end local subject = body.subject if type(subject) ~= "string" then subject = reply_subject(msg.subject) end return { sender = identity, folders = folders, fields = { to = to, cc = cc, bcc = body.bcc, replyTo = body.replyTo, subject = subject, text = body.text, attachments = body.attachments, inReplyTo = inReplyTo, references = references, } } end local function draft_get(id: string, properties: {string}, bodies: boolean?): Invocation return { name = "Email/get", args = { ids = { id }, properties = properties, fetchTextBodyValues = bodies, fetchHTMLBodyValues = bodies } } end -- Refuses a loaded message without the $draft keyword. local function as_draft(operation: string, id: string, data: any): any local msg = data.list and data.list[1] if type(msg) ~= "table" or msg.id ~= id then fail(operation, "Missing message " .. id) end remove_nulls(msg) if type(msg.keywords) ~= "table" or msg.keywords["$draft"] ~= true then error("fastmail." .. operation .. ": message " .. id .. " is not a draft") end return msg end local function draft_of(operation: string, id: string, properties: {string}, bodies: boolean?): any return as_draft(operation, id, call_many({ draft_get(id, properties, bodies) }, operation)[1]) end local function part_text(msg: any, parts: any, mimeType: string): string? local text, truncated = join_parts(msg, parts, mimeType) -- Saving a truncated body would silently shorten the draft. if truncated then error("fastmail: the draft body was truncated; pass text to replace it") end return if text ~= "" then text else nil end local function update_ids(ids: {string}, patch: {[string]: any}, operation: string): {string} local updated: {string} = json.decode("[]") :: {string} for batch in each_chunk(ids) do local update = {} for _, id in batch do update[id] = patch end local data = call("Email/set", { update = update }, operation) for _, id in batch do if type(data.updated) ~= "table" or data.updated[id] == nil then fail(operation, "Missing update confirmation for " .. id) end updated[#updated + 1] = id end end return updated end local function move_to(ids: {string}, dest: string, operation: string): MoveResult return { ids = update_ids(ids, { mailboxIds = { [dest] = true } }, operation), folderId = dest } end local function destroy_ids(ids: any, operation: any) local list = id_list(ids, operation) local gone: {string} = json.decode("[]") :: {string} for batch in each_chunk(list) do local data = call("Email/set", { destroy = batch }, operation) local found: {[string]: boolean} = {} if type(data.destroyed) == "table" then for _, id in data.destroyed do found[id] = true end end for _, id in batch do if not found[id] then fail(operation, "Missing destroy confirmation for " .. id) end gone[#gone + 1] = id end end return { ids = gone } end if houston.allows("data:write") then operationHelp.markRead = [==[markRead(ids) -> {ids}. Marks messages read by setting $seen, preserving other keywords and mailboxes. Accepts one ID or a list of strings/{id} rows. Requires a writable Email token and Write access; Email submission scope is unnecessary. Batches of 50 may partially complete; inspect keywords after a failure before retrying.]==] function functions.markRead(ids: Ids) return { ids = update_ids(id_list(ids, "markRead"), { ["keywords/$seen"] = true }, "markRead") } end operationHelp.markUnread = [==[markUnread(ids) -> {ids}. Marks messages unread by removing $seen, preserving other keywords and mailboxes. Accepts one ID or a list of strings/{id} rows. Requires a writable Email token and Write access; Email submission scope is unnecessary. Batches of 50 may partially complete; inspect keywords after a failure before retrying.]==] function functions.markUnread(ids: Ids) return { ids = update_ids(id_list(ids, "markUnread"), { ["keywords/$seen"] = json.decode("null") }, "markUnread") } end operationHelp.trashMessage = [==[trashMessage(id) -> {id}. Moves a single message to Trash; does not permanently destroy. ID accepts a string or {id}.]==] function functions.trashMessage(id: Id) local moved = move_to({ id_of(id) }, folder_id(functions.listFolders().folders, "trash"), "trashMessage") return { id = moved.ids[1] } end operationHelp.deleteMessage = [==[deleteMessage(ids) -> {ids,folderId}. Moves to Trash; does not permanently destroy. Accepts one ID or list of strings/{id}; batches may partially complete.]==] function functions.deleteMessage(ids: Ids) return move_to(id_list(ids, "deleteMessage"), folder_id(functions.listFolders().folders, "trash"), "deleteMessage") end operationHelp.deleteMessages = [==[deleteMessages(ids) -> {ids,folderId}. Moves to Trash; does not permanently destroy. Accepts one ID or list of strings/{id}; batches of 50 may partially complete. No automatic replay.]==] function functions.deleteMessages(ids: Ids) return functions.deleteMessage(ids) end operationHelp.destroyMessage = [==[destroyMessage(ids) -> {ids}. Permanently destroys messages. Accepts one ID or list of strings/{id}; batches may partially complete. This differs from moving messages to Trash.]==] function functions.destroyMessage(ids: Ids) return destroy_ids(ids, "destroyMessage") end operationHelp.destroyMessages = [==[destroyMessages(ids) -> {ids}. Permanently destroys messages in batches of 50. Accepts one ID or list of strings/{id}. Partial completion is possible; never automatically replay.]==] function functions.destroyMessages(ids: Ids) return functions.destroyMessage(ids) end operationHelp.archiveMessages = [==[archiveMessages(ids) -> {ids,folderId}. Moves to Archive; fails if Archive is absent. Accepts one ID or a list, strings or {id}; batches of 50 may partially complete. No automatic replay.]==] function functions.archiveMessages(ids: Ids): MoveResult local archive = nil for _, folder in functions.listFolders().folders do if folder.role == "archive" then archive = folder.id; break end end if type(archive) ~= "string" or archive == "" then return fail("archiveMessages", "Fastmail has no Archive mailbox") end return move_to(id_list(ids, "archiveMessages"), archive, "archiveMessages") end operationHelp.archiveMessage = [==[archiveMessage(ids) -> {ids,folderId}. Moves to Archive; fails if Archive is absent. Accepts strings or {id} rows, individually or in a list. Alias of archiveMessages; batches may partially complete.]==] function functions.archiveMessage(ids: Ids) return functions.archiveMessages(ids) end operationHelp.moveMessages = [==[moveMessages({ids={...},folder:string}) -> {ids,folderId}. ids accepts one ID or a list; IDs may be strings or {id}. id is also accepted instead of ids for a single message. folder accepts ID or role. Positional moveMessages(ids,folder) remains supported. Replaces mailboxes with one destination, in batches of 50. Partial completion is possible; never automatically replay.]==] function functions.moveMessages(input: Ids | MoveOptions, folder: string?) local ids: any = input if type(ids) == "table" and folder == nil and type(ids.folder) == "string" then folder = ids.folder ids = ids.ids or ids.id end if type(folder) ~= "string" or folder == "" then error("fastmail.moveMessages requires a folder id or role") end return move_to(id_list(ids, "moveMessages"), folder_id(functions.listFolders().folders, folder), "moveMessages") end operationHelp.moveMessage = [==[moveMessage({id:string,folder:string}) -> {ids,folderId}. Replaces message mailboxes with one destination. folder accepts ID or role. Positional moveMessage(id,folder) remains supported; id accepts a string or {id}.]==] function functions.moveMessage(id: Ids | MoveOptions, folder: string?) return functions.moveMessages(id, folder) end operationHelp.createFolder = [==[createFolder({name:string,parentId:string?}) -> {id,name}. parentId is a folder ID or role; parent is also accepted. Omit both for a top-level folder. Positional createFolder(name,parent?) remains supported.]==] function functions.createFolder(input: string | FolderOptions, parent: Id?) local name: any = input if type(name) == "table" and parent == nil then parent = name.parent or name.parentId name = name.name end if type(name) ~= "string" or name == "" then error("fastmail.createFolder requires a name") end local spec: {[string]: any} = { name = name } if parent ~= nil then spec.parentId = folder_id(functions.listFolders().folders, parent) end local data = call("Mailbox/set", { create = { folder = spec } }, "createFolder") local made = data.created and data.created.folder if type(made) ~= "table" or type(made.id) ~= "string" or made.id == "" then fail("createFolder", "Missing folder creation confirmation") end local createdName = if type(made.name) == "string" and made.name ~= "" then made.name else name return { id = made.id, name = createdName } end -- A structured message avoids adding a second MIME/base64 implementation. operationHelp.sendMessage = [==[sendMessage({to={{email=...}},text=...,subject?,identityId?,from?,cc?,bcc?,replyTo?,attachments?}) -> {id,submissionId}. text and nonempty to required; subject defaults empty. Address arrays use {email,name?}. identityId takes precedence over from. Without either, selects identity matching account username or sole identity; ambiguous sender fails. attachments={{path,filename?,mimeType?}} uploads private session files, never inline base64; MIME defaults application/octet-stream, filename defaults path basename. Moves from Drafts to Sent. Email submission scope required. On timeout inspect Drafts and Sent before retrying: delivery may have succeeded.]==] function functions.sendMessage(body: SendOptions): SendResult return submit("sendMessage", compose("sendMessage", body, false)) end operationHelp.replyMessage = [==[replyMessage({id:string,text:string,all:boolean?,subject:string?,identityId:string?,from:string?,to?,cc?,bcc?,replyTo?,attachments?}) -> {id,submissionId}. messageId is also accepted instead of id. Positional replyMessage(id,options) remains supported. Replies to Reply-To, otherwise From; to={{email,name?}} replaces that recipient list. Always preserves thread message IDs/references. all defaults false. Default sender is receiving identity (To then Cc), then primary identity. all=true adds original To/Cc excluding your identities and the To recipients; cc explicitly replaces that list. Subject derives a Re: prefix unless supplied. Attachments use private session paths as in sendMessage. Email submission scope required. Never automatically replay a partial send.]==] function functions.replyMessage(input: Id | ReplyOptions, options: ReplyOptions?): SendResult return submit("replyMessage", compose_reply("replyMessage", input, options, false)) end operationHelp.sendDraft = [==[sendDraft({id,identityId?}) -> {id,submissionId}. Sends an existing draft, such as one from createDraft or createReplyDraft, and moves it from Drafts to Sent, keeping its other folders and keywords. Uses the sending identity matching the draft's From unless identityId is given. Positional sendDraft(id) is supported. Refuses messages that are not drafts. Email submission scope required. On timeout inspect Drafts and Sent before retrying: delivery may have succeeded.]==] function functions.sendDraft(input: Id | SendDraftOptions): SendResult local id = id_of(input) local opts: any = input local identityId = if type(opts) == "table" then opts.identityId else nil local folders, identities, data = mail_context("sendDraft", true, draft_get(id, { "id", "keywords", "from" })) local draft = as_draft("sendDraft", id, data) local from = nil if identityId == nil then local addresses = address_objects(draft.from) if #addresses > 0 then from = addresses[1].email end end local identity = require_identity(identities :: {Identity}, { identityId = identityId, from = from }) return send_email("sendDraft", identity, id, folders) end end -- Draft connections add only draft operations to the reads; the person sends from Fastmail. if houston.allows("data:draft") then local DRAFT_SCOPE = "Needs only the Email scope: without Email submission, identityId is refused and from (default: the account address) is not checked against sending identities." local REVIEW = if houston.allows("data:write") then "The person can review and send it in Fastmail, or send it later with sendDraft." else "Draft connection: this connector never sends; the person reviews and sends drafts in Fastmail." operationHelp.createDraft = [==[createDraft({to?,text,subject?,identityId?,from?,cc?,bcc?,replyTo?,attachments?}) -> {id,threadId}. Saves a draft in Drafts without sending. Options as for sending: address arrays use {email,name?}, but to may be empty; attachments={{path,filename?,mimeType?}} uploads session files. ]==] .. DRAFT_SCOPE .. " " .. REVIEW .. [==[ List drafts with listMessages({folder="drafts"}) and read them with getMessage.]==] function functions.createDraft(body: DraftOptions): DraftResult return save_draft("createDraft", compose("createDraft", body, true)) end operationHelp.createReplyDraft = [==[createReplyDraft({id,text,all?,subject?,identityId?,from?,to?,cc?,bcc?,replyTo?,attachments?}) -> {id,threadId}. Saves a reply in Drafts without sending, so it opens in the original thread. Replies to Reply-To, otherwise From; to replaces that list. all=true adds the original To/Cc except your addresses; cc replaces that list. Subject gets a Re: prefix unless supplied. Keeps In-Reply-To/References. Without Email submission, your addresses are the account address and those the message was delivered to (Fastmail's X-Delivered-To and X-Resolved-To headers): the reply comes from the one it was sent to and all=true leaves them out of Cc; other aliases are unknown, so pass from and cc to override. ]==] .. DRAFT_SCOPE .. " " .. REVIEW function functions.createReplyDraft(input: Id | ReplyOptions, options: ReplyOptions?): DraftResult return save_draft("createReplyDraft", compose_reply("createReplyDraft", input, options, true)) end local DRAFT_PROPERTIES = { "id", "keywords", "mailboxIds", "from", "to", "cc", "bcc", "replyTo", "subject", "inReplyTo", "references", "attachments" } operationHelp.updateDraft = [==[updateDraft({id,to?,cc?,bcc?,replyTo?,subject?,text?,identityId?,from?,attachments?}) -> {id,threadId}. Changes only the given fields of a draft and keeps the rest, including its thread headers. text replaces the body with plain text and drops its inline images; attachments replaces the regular attachments ({} removes them); an empty address list such as cc={} clears that field. Refuses messages that are not drafts. JMAP messages are immutable, so this saves a new draft and destroys the old one: use the returned id. If removing the old version fails, the error names the new draft; delete the old one instead of retrying. ]==] .. DRAFT_SCOPE function functions.updateDraft(input: DraftOptions): DraftResult if type(input) ~= "table" then error("fastmail.updateDraft requires {id, ...}") end local id = id_of(input.id) check_addresses(input, "updateDraft") for _, key in { "subject", "text" } do if input[key] ~= nil and type(input[key]) ~= "string" then error("fastmail.updateDraft " .. key .. " must be a string") end end local keepBody = input.text == nil local properties = table.clone(DRAFT_PROPERTIES) if keepBody then table.move({ "textBody", "htmlBody", "bodyValues" }, 1, 3, #properties + 1, properties) end local explicit = input.identityId ~= nil or input.from ~= nil local verified = verifies(true) -- An unverified sender needs no request, so a bad one is refused before any. local unverified = if explicit and not verified then sender_of(nil, input) else nil local reads = { draft_get(id, properties, keepBody) } if explicit and verified then reads[2] = { name = "Identity/get" } end local results = call_many(reads, "updateDraft") local old = as_draft("updateDraft", id, results[1]) local from = old.from if explicit then local sender = unverified or sender_of(identity_list(results[2]), input) local name = sender.name for _, addr in address_objects(old.from) do if name == nil and lower_email(addr.email) == lower_email(sender.email) then name = addr.name end end from = { { email = sender.email, name = name } } end local text, html = input.text, nil if keepBody then text, html = part_text(old, old.textBody, "text/plain"), part_text(old, old.htmlBody, "text/html") end -- Inline parts belong to the body they appear in; attachments replaces only the others. local attachments = attachment_parts(input.attachments, "updateDraft") or {} local carried: {[string]: boolean} = {} local function carry(part: any, inline: boolean) if type(part.blobId) ~= "string" or carried[part.blobId] then return end carried[part.blobId] = true attachments[#attachments + 1] = { blobId = part.blobId, name = part.name, type = part.type, charset = part.charset, cid = part.cid, disposition = if inline then "inline" else part.disposition, } end if keepBody then -- Media shown inline in the body, outside multipart/related, is listed with the body parts. for _, list in { old.textBody, old.htmlBody } do for _, part in list or {} do if type(part.type) == "string" and string.sub(part.type, 1, 5) ~= "text/" then carry(part, true) end end end end for _, part in old.attachments or {} do local inline = is_inline(part) if (if inline then keepBody else input.attachments == nil) then carry(part, inline) end end local function pick(key: string): any if input[key] ~= nil then return input[key] end return old[key] end local made = create_email("updateDraft", { mailboxIds = old.mailboxIds, keywords = old.keywords, from = from, to = pick("to"), cc = pick("cc"), bcc = pick("bcc"), replyTo = pick("replyTo"), subject = pick("subject"), text = text, html = html, inReplyTo = old.inReplyTo, references = old.references, attachments = nonempty(attachments), }) -- Separate from the create, so a failed create never loses the old draft. local ok, problem = pcall(destroy_ids, id, "updateDraft") if not ok then fail("updateDraft", "Saved new draft " .. made.id .. " but could not remove old draft " .. id .. ": " .. tostring(problem)) end return made end operationHelp.deleteDraft = [==[deleteDraft(id) -> {id}. Permanently destroys a draft; {id} is also accepted. Refuses messages that are not drafts.]==] function functions.deleteDraft(input: Id): {id: string} local id = id_of(input) draft_of("deleteDraft", id, { "id", "keywords" }) return { id = destroy_ids(id, "deleteDraft").ids[1] } end end operationHelp.listMailFolders = [==[listMailFolders() -> {id:string,name:string}[]. No arguments. Includes every available folder, sorted by nonempty unique ID; names may repeat. Empty mailboxes return an empty array; provider failures raise errors.]==] function functions.listMailFolders(...: any): {{id: string, name: string}} if select("#", ...) ~= 0 then error("listMailFolders takes no arguments") end local folders = functions.listFolders().folders if type(folders) ~= "table" then error("mail provider returned invalid folders") end local out: {{id: string, name: string}} = json.decode("[]") local seen = {} for _, folder in (folders :: {any}) do if type(folder.id) ~= "string" or folder.id == "" or type(folder.name) ~= "string" or seen[folder.id] then error("mail provider returned invalid folder metadata") end seen[folder.id] = true out[#out + 1] = { id = folder.id, name = folder.name } end table.sort(out, function(a: any, b: any) return a.id < b.id end) return out end function functions.help(): string local names: {string} = {} for name in (functions :: {[string]: any}) do if name ~= "help" then names[#names + 1] = name end end table.sort(names) local sections = {"fastmail: configured connection help. Operations are synchronous: they return completed results or raise errors; no wait call is needed. Credentials stay on Houston. Use only the functions listed below. Provider scopes are enforced by real calls; help makes no network requests."} for _, name in names do local text = operationHelp[name] assert(text, "missing help for configured function " .. name) sections[#sections + 1] = text end return table.concat(sections, "\n\n") end return functionshouston.json
{ "schema_version": 2, "name": "Fastmail", "verification_key": "bb713b2b43b9d518171d0ad2908658f8a0013a496b155bca12d6c8ddadb2b8e5", "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 in Fastmail, without changing any other mail. It never sends email.", "levels": [ { "value": "read", "label": "Read" }, { "value": "draft", "label": "Draft" }, { "value": "write", "label": "Write" } ], "default": "read" } ], "auth": { "token": { "config": { "token": { "label": "JMAP API token", "required": true, "type": "secret" } }, "label": "JMAP API token", "type": "manual" } }, "proxy": [ { "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } }, "match": { "host": [ "api.fastmail.com", "*.api.fastmail.com", "jmap.fastmail.com" ], "method": [ "GET" ], "path": [ "/jmap/session", "/jmap/download/*" ], "protocol": "http" } }, { "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } }, "match": { "host": [ "api.fastmail.com", "*.api.fastmail.com", "jmap.fastmail.com" ], "method": [ "POST" ], "path": [ "/jmap/api", "/jmap/api/", "/jmap/upload/*" ], "protocol": "http" } }, { "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } }, "match": { "host": [ "fastmailusercontent.com", "*.fastmailusercontent.com" ], "method": [ "GET" ], "path": [ "/jmap/download/*" ], "protocol": "http" } } ] }icon.svg
README.md
--- description: Give agents access to Fastmail to find conversations, organize your inbox, prepare drafts, and send replies. --- # Fastmail Connect agents to your Fastmail inbox so they can find important conversations, read messages, and help you stay on top of email. ## Find what matters - Find emails by person, topic, date, or folder. - Read a whole conversation to catch up on the context. - Download attachments and work with them alongside your other files. ## Prepare replies for you With **Draft** access, agents can also prepare drafts and replies, with attachments, for you to review and send from Fastmail. Reply drafts open in the original conversation. Agents cannot send or change any other mail. ## Keep your inbox moving With **Write** access, agents can also: - Send emails, drafts, or replies to a person or an entire conversation. - Choose which email address to send from and include attachments. - Create folders, move messages, archive finished conversations, and clear out mail you no longer need. - Mark individual messages or batches as read or unread. **Read** cannot change your inbox or send mail.SETUP.md
# Connect Fastmail 1. In Fastmail, open **Settings → Privacy & Security → Manage API tokens**. 2. Create an API token using the **JMAP** protocol. MCP and Dynamic DNS tokens are not supported. 3. Enable **Email**. Also enable **Email submission** if you want agents to send or reply, and **Masked Email** if you want to list masked addresses. 4. In Houston, choose **Access**: - **Read** for browsing, searching, and downloading attachments. - **Draft** to also create, update, and delete drafts that you review and send yourself in Fastmail. Houston never sends with this level. - **Write** to also mark mail read/unread, send drafts, send, reply, create folders, move, archive, or delete mail. Drafts and other changes need a writable **Email** token; **Email submission** is only needed for sending. Leave it off so that even **Write** can prepare drafts but never send them. 5. Paste the token into **JMAP API token** and select **Add connection**. API tokens require a Fastmail plan above Basic. > Write access permits both moving mail to Trash and permanent deletion. Draft > access can permanently delete drafts only.tests
authentication.luau
return { contract = function(m) m.authentication({ { auth = { token = "synthetic-method-secret" }, config = {}, endpoint = { "GET", "https://api.fastmail.com/jmap/session" }, expected = "Bearer synthetic-method-secret", header = "Authorization", method = "token", publisher = {}, }, }) end, }body_formats.luau
return { scenario = {auth_config = {token = "fixture-private-token"}, auth_method = "token", config = {}, publisher = {}}, access = {data = "read"}, configure = function() requests, messages = {}, {} http = {request = function(req) table.insert(requests, req) local data if req.method == "GET" then local mail = "urn:ietf:params:jmap:mail" data = {primaryAccounts = {[mail] = "u1"}, accounts = {u1 = {}}, capabilities = {[mail] = {}}, apiUrl = "https://api.fastmail.com/jmap/api/"} else local call = json.decode(req.body).methodCalls[1] data = {methodResponses = {{call[1], {list = if call[1] == "Thread/get" then {{id = "t1", emailIds = {"m1"}}} else messages}, call[3]}}} end return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode(data))}) end} end, run = function(c) local function raw(plain, html, truncated) return {id = "m1", preview = "Preview", textBody = {{partId = "p", type = "text/plain"}}, htmlBody = {{partId = "h", type = "text/html"}}, bodyValues = {p = if plain ~= nil then {value = plain, isTruncated = truncated == true} else nil, h = if html ~= nil then {value = html} else nil}} end for _, case in { {plain = "\r\n", html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"}, {plain = " \t\r\n", html = "<p>Newsletter</p>", format = "auto", want = "<p>Newsletter</p>"}, {plain = "", html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"}, {plain = utf8.char(0xA0, 0x2003), html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"}, {plain = " Text\n", html = "<p>Newsletter</p>", want = " Text\n"}, {plain = "Text", html = " <p>HTML</p>\n", format = "html", want = " <p>HTML</p>\n"}, {plain = "\r\n", html = "<p>Newsletter</p>", format = "text", want = "\r\n"}, {html = "<p>Newsletter</p>", format = "text", want = ""}, {plain = "Text", format = "html", want = ""}, {plain = " \n", html = "\r\n", want = "Preview"}, {plain = " ", html = "<p>HTML</p>", truncated = true, want = " ", wantTruncated = true}, {plain = "Text", html = "<p>HTML</p>", truncated = true, format = "html", want = "<p>HTML</p>"}, } do messages = {raw(case.plain, case.html, case.truncated)} local m = c.getMessage({id = "m1", bodyFormat = case.format}) assert(m.body == case.want, "body mismatch: " .. json.encode(m.body)) assert(m.bodyTruncated == (case.wantTruncated == true), "selected body truncation") local args = json.decode(requests[#requests].body).methodCalls[1][2] assert(args.fetchTextBodyValues == (case.format ~= "html") and args.fetchHTMLBodyValues == (case.format ~= "text")) end messages = {raw("Plain", "<p>HTML</p>")} assert(c.getMessages({ids = {"m1"}, bodyFormat = "html"})[1].body == "<p>HTML</p>") assert(c.getThread({id = "t1", bodyFormat = "html"}).messages[1].body == "<p>HTML</p>") assert(c.getMessage("m1", {bodyFormat = "html"}).body == "<p>HTML</p>") assert(c.getMessages({"m1"}, {bodyFormat = "html"})[1].body == "<p>HTML</p>") messages[1].textBody = {{partId = "h", type = "text/html"}} assert(c.getMessage({id = "m1", bodyFormat = "text"}).body == "", "JMAP textBody can contain HTML") assert(c.getMessage({id = "m1"}).body == "<p>HTML</p>") messages[1].htmlBody = {{partId = "p", type = "text/plain"}, {partId = "h", type = "text/html"}} assert(c.getMessage({id = "m1", bodyFormat = "html"}).body == "<p>HTML</p>") messages[1].textBody = messages[1].htmlBody assert(c.getMessage({id = "m1"}).body == "Plain\n<p>HTML</p>", "automatic rendering must retain mixed body parts") for _, format in {"", "markdown", false, 3} do local count = #requests assert(not pcall(c.getMessage, {id = "m1", bodyFormat = format})) assert(not pcall(c.getMessages, {ids = {"m1"}, bodyFormat = format})) assert(not pcall(c.getThread, {id = "t1", bodyFormat = format})) assert(#requests == count, "invalid body format reached Fastmail") end end, }contract.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "read"}, run = function(exports) assert(exports.sendMessage == nil, "Read access must omit write exports") for _, name in {"sendMessage", "replyMessage", "trashMessage", "deleteMessage", "deleteMessages", "destroyMessage", "destroyMessages", "archiveMessage", "archiveMessages", "createFolder", "moveMessage", "moveMessages", "markRead", "markUnread", "createDraft", "createReplyDraft", "updateDraft", "deleteDraft", "sendDraft"} do assert(exports[name] == nil, "Read access must omit " .. name) end assert(type(exports.listAliases) == "function") assert(type(exports.listIdentities) == "function") assert(type(exports.getAttachment) == "function") local count = 0 for name, fn in exports do assert(type(name) == "string" and type(fn) == "function") count += 1 end assert(count > 0) end}domain_empty.luau
return { scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "fixture-private-token"}}, configure = function() requests = 0 http = {request = function(_request) requests += 1 if requests == 1 then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode({username = "[email protected]", primaryAccounts = {["urn:ietf:params:jmap:mail"] = "account"}, accounts = {account = {name = "Account"}}, apiUrl = "https://api.fastmail.com/jmap/api/"}))}) end return fixture.operation({statusCode=200, headers={}, body=fixture.reader('{"methodResponses":[["Mailbox/get",{"list":[]},"0"]]}')}) end} end, run = function(exports) assert(not pcall(exports.listMailFolders, "unexpected")) local folders = exports.listMailFolders() assert(#folders == 0) assert(json.encode(folders) == "[]", "empty folders must remain a JSON array") end, }domain_folders.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},configure=function() calls=0 http={request=function(req) calls+=1 if calls==1 then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode({username="[email protected]",primaryAccounts={["urn:ietf:params:jmap:mail"]="account"},accounts={account={name="Account"}},apiUrl="https://api.fastmail.com/jmap/api/"}))}) end return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode({methodResponses={{"Mailbox/get",{list={{id="z",name="Archive",role="archive"},{id="a",name="Inbox",role="inbox"}}},"0"}}}))}) end} end,run=function(c) local folders=c.listMailFolders() assert(#folders==2 and folders[1].id=="a" and folders[1].name=="Inbox") assert(folders[2].id=="z" and folders[2].name=="Archive") assert(folders[1].role==nil) end}drafts_with_submission.luau
-- With Email submission, draft senders are verified identities and drafts can be sent. return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req assert(#responses > 0, "unexpected request: " .. tostring(req.url)) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" function session() return {username="[email protected]", primaryAccounts={[MAIL]="u1"}, accounts={u1={name="Me"}}, capabilities={[MAIL]={}, [SUB]={}}, apiUrl="https://api.fastmail.com/jmap/api/"} end function result(name, args) return {methodResponses={{name, args, "0"}}} end function results(...) local out = {} for index, item in {...} do out[index] = {item[1], item[2], tostring(index - 1)} end return {methodResponses=out} end folders={{id="in", role="inbox", name="Inbox"}, {id="dr", role="drafts", name="Drafts"}, {id="se", role="sent", name="Sent"}} identities={list={{id="i-me", email="[email protected]", name="Me"}, {id="i-sup", email="[email protected]", name="Support"}, {id="i-any", email="*@team.example.com", name="Team"}}} function draft(id, keywords) return {id=id, keywords=keywords or {["$draft"]=true}, from={{name="Support", email="[email protected]"}}} end function jmapSince(start) local out = {} for i = start + 1, #requests do local decoded = json.decode(requests[i].body) for _, methodCall in decoded.methodCalls do out[#out + 1] = {name=methodCall[1], args=methodCall[2], using=decoded.using} end end return out end end, run=function(fastmail) responses={session(), results({"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d1", threadId="t1"}}})} local made = fastmail.createDraft({to={{email="[email protected]"}}, text="Body", from="[email protected]"}) assert(made.id == "d1") local calls = jmapSince(1) assert(#calls == 3 and calls[2].name == "Identity/get" and #requests == 3) local created = calls[3].args.create.draft assert(created.from[1].email == "[email protected]" and created.from[1].name == "Support") responses={results({"Mailbox/get", {list=folders}}, {"Identity/get", identities})} local mark = #requests local ok, err = pcall(function() fastmail.createDraft({text="x", from="[email protected]"}) end) assert(not ok and string.find(tostring(err), "listAliases", 1, true) and #requests == mark + 1) responses={results({"Email/get", {list={draft("d1")}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("EmailSubmission/set", {created={send={id="s1"}}})} mark = #requests local sent = fastmail.sendDraft({id="d1"}) assert(sent.id == "d1" and sent.submissionId == "s1") calls = jmapSince(mark) assert(#calls == 4 and calls[1].name == "Email/get" and calls[4].name == "EmailSubmission/set" and #requests == mark + 2) local submission = calls[4].args assert(submission.create.send.emailId == "d1" and submission.create.send.identityId == "i-sup") assert(calls[4].using[3] == "urn:ietf:params:jmap:submission") assert(submission.onSuccessUpdateEmail["#send"]["mailboxIds/se"] == true and submission.onSuccessUpdateEmail["#send"].keywords == nil) assert(string.find(requests[#requests].body, "\"mailboxIds/dr\":null", 1, true)) assert(string.find(requests[#requests].body, "\"keywords/$draft\":null", 1, true)) responses={results({"Email/get", {list={draft("d1")}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("EmailSubmission/set", {created={send={id="s2"}}})} mark = #requests sent = fastmail.sendDraft({id="d1", identityId="i-me"}) assert(sent.submissionId == "s2" and jmapSince(mark)[4].args.create.send.identityId == "i-me") responses={results({"Email/get", {list={draft("m", {["$seen"]=true})}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities})} mark = #requests ok, err = pcall(function() fastmail.sendDraft("m") end) assert(not ok and string.find(tostring(err), "not a draft", 1, true) and #requests == mark + 1) responses={results({"Email/get", {list={draft("d1")}}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d2"}}}), result("Email/set", {destroyed={"d1"}})} mark = #requests made = fastmail.updateDraft({id="d1", from="[email protected]", text="Changed"}) assert(made.id == "d2") assert(#requests == mark + 3, "the draft and identities share one request") calls = jmapSince(mark) created = calls[3].args.create.draft assert(created.from[1].email == "[email protected]" and created.from[1].name == "Me" and created.bodyValues.text.value == "Changed") assert(calls[4].args.destroy[1] == "d1") -- A wildcard identity sends from any address at its domain. local wild = {id="dw", keywords={["$draft"]=true}, from={{email="[email protected]"}}} responses={results({"Email/get", {list={wild}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("EmailSubmission/set", {created={send={id="s4"}}})} mark = #requests assert(fastmail.sendDraft("dw").submissionId == "s4" and jmapSince(mark)[4].args.create.send.identityId == "i-any") -- A failed follow-up update after a successful submission must not invite a resend. responses={results({"Email/get", {list={draft("d2")}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), {methodResponses={{"EmailSubmission/set", {created={send={id="s5"}}}, "0"}, {"Email/set", {notUpdated={d2={type="serverFail"}}}, "0"}}}} ok, err = pcall(function() fastmail.sendDraft("d2") end) assert(not ok and string.find(tostring(err), "do not retry", 1, true) and string.find(tostring(err), "d2: serverFail", 1, true)) assert(#responses == 0) end}drafts_without_submission.luau
-- A token without Email submission prepares drafts but never sends. return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req if req.body ~= nil and type(req.body) ~= "string" then assert(await(req.body:readAll()) == "payload") await(req.body:close()) end assert(#responses > 0, "unexpected request: " .. tostring(req.url)) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} fs = fixture.files() local input = fs.open("files/brief.pdf", "w") input:write("payload") await(input:close()) local MAIL="urn:ietf:params:jmap:mail" local CORE="urn:ietf:params:jmap:core" local SUB="urn:ietf:params:jmap:submission" function session() -- The server supports submission, but this token's account may not use it. return {username="[email protected]", primaryAccounts={[MAIL]="u1"}, accounts={u1={name="Me", accountCapabilities={[MAIL]={}}}}, capabilities={[CORE]={}, [MAIL]={}, [SUB]={}}, apiUrl="https://api.fastmail.com/jmap/api/", uploadUrl="https://api.fastmail.com/jmap/upload/{accountId}/"} end function result(name, args) return {methodResponses={{name, args, "0"}}} end function results(...) local out = {} for index, item in {...} do out[index] = {item[1], item[2], tostring(index - 1)} end return {methodResponses=out} end folders={{id="in", role="inbox", name="Inbox"}, {id="dr", role="drafts", name="Drafts"}, {id="se", role="sent", name="Sent"}} function original() return {id="m", messageId={"<[email protected]>"}, references={"<[email protected]>"}, from={{name="Sender", email="[email protected]"}}, replyTo=json.decode("null"), to={{email="[email protected]"}, {email="[email protected]"}}, cc={{email="[email protected]"}}, subject="Hello"} end function saved(id, extra) local msg = {id=id, keywords={["$draft"]=true, ["$seen"]=true}, mailboxIds={dr=true}, from={{name="Me", email="[email protected]"}}, to={{email="[email protected]"}}, cc={{email="[email protected]"}}, bcc=json.decode("null"), replyTo=json.decode("null"), subject="Re: Hello", inReplyTo={"<[email protected]>"}, references={"<[email protected]>", "<[email protected]>"}, attachments={{blobId="b1", name="a.csv", type="text/csv", charset="iso-8859-1", disposition="attachment", cid=json.decode("null")}, {blobId="img", name="logo.png", type="image/png", disposition=json.decode("null"), cid="c1"}, {blobId="b2", name="b.pdf", type="application/pdf", disposition="attachment", cid="x2"}}} for key, value in extra or {} do msg[key] = value end return msg end function jmapSince(start) local out = {} for i = start + 1, #requests do local req = requests[i] if type(req.body) == "string" then local decoded = json.decode(req.body) for _, methodCall in decoded.methodCalls do out[#out + 1] = {name=methodCall[1], args=methodCall[2]} end elseif req.body ~= nil then out[#out + 1] = {name="upload", req=req} end end return out end end, run=function(fastmail) responses={session(), result("Mailbox/get", {list=folders}), {blobId="blob1", type="application/pdf", size=7}, result("Email/set", {created={draft={id="d1", threadId="t1"}}})} local made = fastmail.createDraft({subject="Plan", text="Draft body", attachments={{path="files/brief.pdf", mimeType="application/pdf"}}}) assert(made.id == "d1" and made.threadId == "t1") local calls = jmapSince(0) assert(#calls == 3 and calls[1].name == "Mailbox/get" and calls[2].name == "upload" and calls[3].name == "Email/set") local draft = calls[3].args.create.draft assert(draft.from[1].email == "[email protected]" and draft.to == nil and draft.subject == "Plan") assert(draft.mailboxIds.dr and draft.keywords["$draft"] and draft.keywords["$seen"]) assert(draft.bodyValues.text.value == "Draft body" and draft.htmlBody == nil) assert(draft.attachments[1].blobId == "blob1" and draft.attachments[1].name == "brief.pdf") local mark = #requests local ok, err = pcall(function() fastmail.createDraft({text="x", identityId="i"}) end) assert(not ok and string.find(tostring(err), "Email submission", 1, true) and #requests == mark) ok, err = pcall(function() fastmail.createDraft({text="x", from="Support"}) end) assert(not ok and string.find(tostring(err), "email address", 1, true) and #requests == mark) ok, err = pcall(function() fastmail.replyMessage("m", {text="x"}) end) assert(not ok and string.find(tostring(err), "Email submission", 1, true) and #requests == mark) responses={results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}), result("Email/set", {created={draft={id="d2", threadId="t-orig"}}})} mark = #requests made = fastmail.createReplyDraft({id="m", text="Thanks", all=true}) assert(made.id == "d2" and made.threadId == "t-orig") calls = jmapSince(mark) assert(#calls == 3 and calls[1].name == "Email/get" and calls[2].name == "Mailbox/get") assert(#requests == mark + 2, "the original message and folders share one request") local wanted = {} for _, property in calls[1].args.properties do wanted[property] = true end assert(wanted["header:X-Delivered-To:asAddresses:all"] and wanted["header:X-Resolved-To:asAddresses:all"]) draft = calls[3].args.create.draft assert(draft.from[1].email == "[email protected]" and draft.subject == "Re: Hello") assert(draft.to[1].email == "[email protected]" and #draft.cc == 2 and draft.cc[1].email == "[email protected]") assert(draft.inReplyTo[1] == "<[email protected]>" and draft.references[1] == "<[email protected]>" and draft.references[2] == "<[email protected]>") assert(draft.keywords["$draft"] and draft.mailboxIds.dr) local toAlias = original() toAlias.to = {{email="[email protected]"}, {email="[email protected]"}} -- Fastmail's header comes first; a later instance from the sender must not count as yours. toAlias["header:X-Delivered-To:asAddresses:all"] = {{{email="[email protected]"}}, {{email="[email protected]"}}} toAlias["header:X-Resolved-To:asAddresses:all"] = {{{email="[email protected]"}}} responses={results({"Email/get", {list={toAlias}}}, {"Mailbox/get", {list=folders}}), result("Email/set", {created={draft={id="d-alias"}}})} mark = #requests assert(fastmail.createReplyDraft({id="m", text="Thanks", all=true}).id == "d-alias") draft = jmapSince(mark)[3].args.create.draft assert(draft.from[1].email == "[email protected]", "a reply comes from the alias the message was delivered to") assert(#draft.cc == 2 and draft.cc[1].email == "[email protected]" and draft.cc[2].email == "[email protected]") responses={result("Email/get", {list={saved("d2", {textBody={{partId="1", type="text/plain"}}, htmlBody={{partId="2", type="text/html"}}, bodyValues={["1"]={value="Hi"}, ["2"]={value="<p>Hi</p>"}}})}}), result("Email/set", {created={draft={id="d3", threadId="t-orig"}}}), result("Email/set", {destroyed={"d2"}})} mark = #requests made = fastmail.updateDraft({id="d2", subject="Re: Hello again", cc={}}) assert(made.id == "d3") calls = jmapSince(mark) assert(#calls == 3 and calls[1].args.fetchTextBodyValues and calls[1].args.fetchHTMLBodyValues) draft = calls[2].args.create.draft assert(draft.subject == "Re: Hello again" and draft.cc == nil and draft.to[1].email == "[email protected]") assert(draft.from[1].email == "[email protected]" and draft.keywords["$draft"] and draft.mailboxIds.dr) assert(draft.bodyValues.text.value == "Hi" and draft.bodyValues.html.value == "<p>Hi</p>" and draft.htmlBody[1].type == "text/html") assert(#draft.attachments == 3 and draft.attachments[3].blobId == "b2" and draft.attachments[1].blobId == "b1" and draft.attachments[1].name == "a.csv" and draft.attachments[1].disposition == "attachment") assert(draft.attachments[1].charset == "iso-8859-1" and draft.attachments[2].cid == "c1" and draft.attachments[2].disposition == "inline") assert(draft.inReplyTo[1] == "<[email protected]>" and #draft.references == 2) assert(calls[3].args.destroy[1] == "d2" and calls[3].args.create == nil) responses={result("Email/get", {list={saved("d3")}}), result("Email/set", {created={draft={id="d4"}}}), result("Email/set", {destroyed={"d3"}})} mark = #requests made = fastmail.updateDraft({id="d3", text="New body", from="[email protected]", attachments={}}) assert(made.id == "d4" and made.threadId == nil) calls = jmapSince(mark) assert(#calls == 3 and not calls[1].args.fetchTextBodyValues) for _, property in calls[1].args.properties do assert(property ~= "bodyValues") end draft = calls[2].args.create.draft assert(draft.from[1].email == "[email protected]" and draft.from[1].name == "Me" and draft.bodyValues.text.value == "New body") assert(draft.htmlBody == nil and draft.attachments == nil and draft.subject == "Re: Hello") responses={result("Email/get", {list={saved("m", {keywords={["$seen"]=true}})}})} mark = #requests ok, err = pcall(function() fastmail.updateDraft({id="m", subject="x"}) end) assert(not ok and string.find(tostring(err), "not a draft", 1, true) and #requests == mark + 1) responses={result("Email/get", {list={saved("d4", {textBody={{partId="1", type="text/plain"}, {blobId="pic", name="pic.jpg", type="image/jpeg", disposition="inline"}}, htmlBody={{partId="2", type="text/html"}}, bodyValues={["1"]={value="Hi"}, ["2"]={value="<p>Hi <img src=\"cid:c1\"></p>"}}})}}), {blobId="blob1", type="application/pdf", size=7}, result("Email/set", {created={draft={id="d5"}}}), result("Email/set", {notDestroyed={d4={type="serverFail"}}})} mark = #requests ok, err = pcall(function() fastmail.updateDraft({id="d4", attachments={{path="files/brief.pdf"}}}) end) assert(not ok and string.find(tostring(err), "Saved new draft d5", 1, true) and string.find(tostring(err), "old draft d4", 1, true)) calls = jmapSince(mark) assert(#calls == 4 and calls[2].name == "upload") draft = calls[3].args.create.draft assert(#draft.attachments == 3 and draft.attachments[1].blobId == "blob1" and draft.attachments[2].blobId == "pic" and draft.attachments[3].blobId == "img") assert(draft.attachments[2].disposition == "inline" and draft.attachments[3].disposition == "inline") assert(draft.bodyValues.html.value == "<p>Hi <img src=\"cid:c1\"></p>") responses={result("Email/get", {list={saved("d5")}}), result("Email/set", {destroyed={"d5"}})} mark = #requests assert(fastmail.deleteDraft({id="d5"}).id == "d5") calls = jmapSince(mark) assert(#calls == 2 and calls[2].args.destroy[1] == "d5") responses={result("Email/get", {list={saved("m", {keywords={["$seen"]=true}})}})} mark = #requests ok, err = pcall(function() fastmail.deleteDraft("m") end) assert(not ok and string.find(tostring(err), "not a draft", 1, true) and #requests == mark + 1) mark = #requests ok, err = pcall(function() fastmail.sendDraft("d4") end) assert(not ok and string.find(tostring(err), "Email submission", 1, true) and #requests == mark) mark = #requests ok, err = pcall(function() fastmail.updateDraft({id="d1", identityId="i"}) end) assert(not ok and string.find(tostring(err), "Email submission", 1, true) and #requests == mark) responses={result("Email/get", {list={saved("d6", {textBody={{partId="1", type="text/plain"}}, htmlBody={{partId="1", type="text/plain"}}, bodyValues={["1"]={value="Cut", isTruncated=true}}})}})} mark = #requests ok, err = pcall(function() fastmail.updateDraft({id="d6", subject="x"}) end) assert(not ok and string.find(tostring(err), "truncated", 1, true) and #requests == mark + 1) -- An explicit from stays out of reply-all Cc even when it is not a delivery address. responses={results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}), result("Email/set", {created={draft={id="d7"}}})} mark = #requests fastmail.createReplyDraft({id="m", text="Thanks", all=true, from="[email protected]"}) draft = jmapSince(mark)[3].args.create.draft assert(draft.from[1].email == "[email protected]" and #draft.cc == 1 and draft.cc[1].email == "[email protected]") local profile = fastmail.getProfile() assert(not profile.canSend) for _, name in profile.capabilities do assert(name ~= "urn:ietf:params:jmap:submission") end assert(#responses == 0) end}empty_collections.luau
return { scenario = {auth_method = "token", auth_config = {token = "fixture-private-token"}, config = {}, publisher = {}}, access = {data = "read"}, configure = function() requests, responses = {}, {} http = {request = function(request) requests[#requests + 1] = request local response = table.remove(responses, 1) assert(response, "unexpected request: " .. request.url) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} function result(name, data) return {methodResponses = {{name, data, "0"}}} end responses = { { username = "[email protected]", primaryAccounts = {["urn:ietf:params:jmap:mail"] = "u1"}, accounts = {u1 = {name = "Me"}}, capabilities = {}, apiUrl = "https://api.fastmail.com/jmap/api/", }, result("Email/query", {ids = json.decode("[]"), position = 0, total = 0}), result("Email/query", {ids = json.decode("[]"), position = 0, total = 0}), result("Thread/get", {list = {{id = "empty", emailIds = json.decode("[]")}}}), result("Email/get", {list = {{id = "m", attachments = json.decode("[]")}}}), result("Email/get", {list = {{id = "m", attachments = json.decode("[]")}}}), } end, run = function(fastmail) assert(json.encode(fastmail.listMessages({includeSpamTrash = true}).messages) == "[]") assert(json.encode(fastmail.listThreads({includeSpamTrash = true}).threads) == "[]") assert(json.encode(fastmail.getThread("empty").messages) == "[]") assert(json.encode(fastmail.listAttachments("m")) == "[]") local message = fastmail.getMessage("m") assert(json.encode(message.attachments) == "[]" and json.encode(message.received) == "[]") assert(json.encode(fastmail.getAttachments({messageId = "m", items = {}})) == "[]") assert(#responses == 0 and #requests == 6, "empty selections and threads must not fetch bodies") end, }fastmail_alias_scope_and_upstream_errors.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req assert(#responses > 0, "unexpected request: " .. tostring(req.url)) local response = table.remove(responses, 1) if type(response) == "string" then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(response)}) end if type(response) == "table" and response.statusCode then return fixture.operation({statusCode=response.statusCode, headers={}, body=fixture.reader(response.body or "")}) end return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} local MAIL="urn:ietf:params:jmap:mail" function session() return {username="[email protected]", primaryAccounts={[MAIL]="u1"}, accounts={u1={name="Me"}}, capabilities={[MAIL]={}}, apiUrl="https://api.fastmail.com/jmap/api/"} end function result(name, args) return {methodResponses={{name, args, "0"}}} end end, run=function(fastmail) responses={session(), {statusCode=401, body="No Authorization header"}, {statusCode=200, body="not-json"}, result("Mailbox/get", {list={{id="in", role="inbox", name="Inbox"}, {id="tr", role="trash", name="Trash"}}})} local ok, err = pcall(fastmail.listAliases) assert(not ok) local text = tostring(err) assert(string.find(text, "Email submission", 1, true) and string.find(text, "Masked Email", 1, true)) assert(#requests == 1) assert(type(fastmail.sendMessage) == "function", "manual token scopes are unknown at discovery") ok, err = pcall(fastmail.sendMessage, {to={{email="[email protected]"}}, text="Do not send"}) assert(not ok and string.find(tostring(err), "Email submission", 1, true)) assert(#requests == 1, "missing submission scope must fail before draft or send") ok, err = pcall(fastmail.listFolders) assert(not ok and string.find(tostring(err), "upstream HTTP 401", 1, true) and string.find(tostring(err), "No Authorization header", 1, true)) ok, err = pcall(fastmail.listFolders) assert(not ok and string.find(tostring(err), "invalid JSON", 1, true)) ok, err = pcall(fastmail.archiveMessages, "m") assert(not ok and string.find(tostring(err), "no Archive mailbox", 1, true)) assert(#responses == 0) -- Provider protocol errors must stay structured, including malformed -- error payloads and automatic follow-up method responses. for _, malformed in { true, 17, {methodResponses={{"error", "not an object", "0"}}}, {methodResponses={{"Mailbox/get", {list={}}, "0"}, {"Email/set", false, "0"}}}, } do responses={malformed} ok, err = pcall(fastmail.listFolders) assert(not ok) text = tostring(err) assert(string.find(text, '"layer":"upstream"', 1, true), "malformed JMAP responses need upstream context: " .. text) assert(#responses == 0) end end}fastmail_aliases_folders_replies_and_attachments.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req if req.body ~= nil and type(req.body) ~= "string" then assert(await(req.body:readAll()) == string.char(0,255) .. "payload!") await(req.body:close()) end assert(#responses > 0, "unexpected request: " .. tostring(req.url)) local response = table.remove(responses, 1) if type(response) == "string" then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(response)}) end if response.statusCode then return fixture.operation({statusCode=response.statusCode, headers={}, body=fixture.reader(response.body or "")}) end return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} fs = fixture.files() local input = fs.open("files/brief.pdf", "w") input:write(string.char(0,255) .. "payload!") await(input:close()) local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" local MASKED="https://www.fastmail.com/dev/maskedemail" local CORE="urn:ietf:params:jmap:core" function session() return {username="[email protected]", primaryAccounts={[MAIL]="u1", [MASKED]="m1"}, accounts={u1={name="Me"}}, capabilities={[CORE]={}, [MAIL]={}, [SUB]={}, [MASKED]={}}, apiUrl="https://phl.api.fastmail.com/jmap/api/", uploadUrl="https://phl.api.fastmail.com/jmap/upload/{accountId}/", downloadUrl="https://www.fastmailusercontent.com/jmap/download/{accountId}/{blobId}/{name}?type={type}"} end function result(name, args) return {methodResponses={{name, args, "0"}}} end function results(...) local out = {} for index, item in {...} do out[index] = {item[1], item[2], tostring(index - 1)} end return {methodResponses=out} end folders={{id="in", role="inbox", name="Inbox"}, {id="tr", role="trash", name="Trash"}, {id="sp", role="junk", name="Spam"}, {id="dr", role="drafts", name="Drafts"}, {id="se", role="sent", name="Sent"}, {id="ar", role="archive", name="Archive"}} identities={list={{id="i-me", email="[email protected]", name="Me"}, {id="i-sup", email="[email protected]", name="Support"}}} masked={list={{id="mask-sup", email="[email protected]", state="enabled", description="Support", forDomain="example.com"}, {id="mask-admin", email="[email protected]", state="enabled", description="Billing", forDomain="example.com"}}} function original() return {id="m", messageId={"<[email protected]>"}, references={"<[email protected]>", "<[email protected]>"}, from={{name="Sender", email="[email protected]"}}, replyTo=json.decode("null"), to={{email="[email protected]"}, {email="[email protected]"}}, cc={{email="[email protected]"}}, subject="Hello"} end function bare() return {id="m2", messageId=json.decode("null"), from={{email="[email protected]"}}, to={{email="[email protected]"}}, subject="Re: Hello"} end function jmapSince(start) local out = {} for i = start + 1, #requests do local req = requests[i] if req.body ~= nil and type(req.body) ~= "string" then out[#out + 1] = {upload=req} elseif type(req.body) == "string" then local decoded = json.decode(req.body) for _, methodCall in decoded.methodCalls do out[#out + 1] = {name=methodCall[1], args=methodCall[2], using=decoded.using, req=req} end end end return out end end, run=function(fastmail) responses={session(), result("Identity/get", identities), result("MaskedEmail/get", masked), result("Mailbox/get", {list=folders}), result("Email/query", {ids={"m"}, position=0, total=1}), results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d1"}}}), result("EmailSubmission/set", {created={send={id="s1"}}}), results({"Email/get", {list={bare()}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d2"}}}), result("EmailSubmission/set", {created={send={id="s2"}}}), results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d3"}}}), result("EmailSubmission/set", {created={send={id="s3"}}}), results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Email/set", {created={draft={id="d5"}}}), result("EmailSubmission/set", {created={send={id="s5"}}}), results({"Email/get", {list={original()}}}, {"Mailbox/get", {list=folders}}, {"Identity/get", identities}), result("Mailbox/get", {list=folders}), result("Mailbox/set", {created={folder={id="f1", name="Projects"}}}), result("Mailbox/get", {list=folders}), result("Email/set", json.decode([[{"updated":{"a":null,"b":null}}]])), result("Mailbox/get", {list=folders}), result("Email/set", json.decode([[{"updated":{"c":null}}]])), result("Mailbox/get", {list=folders}), result("Email/set", json.decode([[{"updated":{"a":null,"b":null}}]])), result("Email/set", {destroyed={"a"}}), results({"Mailbox/get", {list=folders}}, {"Identity/get", identities}), {blobId="blob1", type="application/pdf", size=10}, result("Email/set", {created={draft={id="d4"}}}), result("EmailSubmission/set", {created={send={id="s4"}}})} local mark = #requests local listed = fastmail.listAliases() local calls = jmapSince(mark) assert(#calls == 2 and calls[1].name == "Identity/get" and calls[2].name == "MaskedEmail/get") assert(calls[2].args.accountId == "m1") assert(calls[2].using[3] == "https://www.fastmail.com/dev/maskedemail") assert(json.encode(listed.notes) == "[]") local by = {} for _, alias in listed.aliases do by[alias.email] = alias end assert(by["[email protected]"].canSend and by["[email protected]"].masked and by["[email protected]"].identityId == "i-sup") assert(by["[email protected]"].masked and not by["[email protected]"].canSend and by["[email protected]"].name == "Billing") assert(by["[email protected]"].canSend and not by["[email protected]"].masked) local profile = fastmail.getProfile() assert(profile.canSend and profile.emailAddress == "[email protected]" and profile.accountId == "u1") assert(profile.capabilities[1] == "https://www.fastmail.com/dev/maskedemail") mark = #requests local page = fastmail.listMessages({alias="[email protected]", from="[email protected]", folder="INBOX"}) assert(page.messages[1].id == "m") calls = jmapSince(mark) local conditions = calls[2].args.filter.conditions assert(#conditions == 3 and conditions[1].from == "[email protected]" and conditions[3].inMailbox == "in") assert(conditions[2].operator == "OR" and #conditions[2].conditions == 4) local keys = {} for _, item in conditions[2].conditions do for k, v in item do keys[k] = v end end assert(keys.to == "[email protected]" and keys.cc == "[email protected]" and keys.bcc == "[email protected]" and keys.from == "[email protected]") mark = #requests local sent = fastmail.replyMessage("m", {text="Thanks"}) assert(sent.id == "d1" and sent.submissionId == "s1") calls = jmapSince(mark) local draft = calls[4].args.create.draft assert(calls[4].name == "Email/set" and draft.from[1].email == "[email protected]") assert(draft.subject == "Re: Hello" and draft.to[1].email == "[email protected]" and draft.cc == nil) assert(draft.inReplyTo[1] == "<[email protected]>" and #draft.references == 2) assert(draft.references[1] == "<[email protected]>" and draft.references[2] == "<[email protected]>") assert(calls[5].args.create.send.identityId == "i-sup") mark = #requests sent = fastmail.replyMessage({id="m2", text="Again", from="[email protected]"}) assert(sent.id == "d2") calls = jmapSince(mark) draft = calls[4].args.create.draft assert(draft.from[1].email == "[email protected]" and draft.subject == "Re: Hello") assert(draft.inReplyTo == nil and draft.references == nil) assert(calls[5].args.create.send.identityId == "i-me") mark = #requests fastmail.replyMessage("m", {text="All", all=true}) calls = jmapSince(mark) draft = calls[4].args.create.draft assert(draft.to[1].email == "[email protected]" and #draft.cc == 2) assert(draft.cc[1].email == "[email protected]" and draft.cc[2].email == "[email protected]") mark = #requests fastmail.replyMessage("m", {text="Both", all=true, to={{email="[email protected]"}, {email="[email protected]", name="Other"}}}) calls = jmapSince(mark) draft = calls[4].args.create.draft assert(#draft.to == 2 and draft.to[1].email == "[email protected]" and draft.to[2].name == "Other") assert(#draft.cc == 1 and draft.cc[1].email == "[email protected]") assert(draft.inReplyTo[1] == "<[email protected]>" and draft.references[2] == "<[email protected]>") mark = #requests for _, to in {{}, {{email="[email protected]"}, "[email protected]"}} do local ok, err = pcall(function() fastmail.replyMessage("m", {text="Nobody", to=to}) end) assert(not ok and string.find(tostring(err), "nonempty", 1, true) and #requests == mark) end mark = #requests local ok, err = pcall(function() fastmail.replyMessage("m", {text="Nope", from="[email protected]"}) end) assert(not ok and string.find(tostring(err), "[email protected]", 1, true) and string.find(tostring(err), "listAliases", 1, true)) calls = jmapSince(mark) assert(#calls == 3 and calls[3].name == "Identity/get") mark = #requests local folder = fastmail.createFolder("Projects", "INBOX") assert(folder.id == "f1" and folder.name == "Projects") calls = jmapSince(mark) assert(calls[2].name == "Mailbox/set" and calls[2].args.create.folder.name == "Projects" and calls[2].args.create.folder.parentId == "in") mark = #requests local moved = fastmail.moveMessages({"a", "b"}, "archive") assert(moved.folderId == "ar" and moved.ids[1] == "a" and moved.ids[2] == "b") calls = jmapSince(mark) assert(calls[2].args.update.a.mailboxIds.ar and not calls[2].args.update.a.mailboxIds["in"]) assert(calls[2].args.update.b.mailboxIds.ar) mark = #requests local archived = fastmail.archiveMessages("c") assert(archived.folderId == "ar" and archived.ids[1] == "c") calls = jmapSince(mark) assert(#calls == 2 and calls[2].args.update.c.mailboxIds.ar) mark = #requests local deleted = fastmail.deleteMessages({"a", "b"}) assert(deleted.folderId == "tr") calls = jmapSince(mark) assert(calls[2].args.update.a.mailboxIds.tr and calls[2].args.destroy == nil) mark = #requests local destroyed = fastmail.destroyMessage("a") assert(destroyed.ids[1] == "a") calls = jmapSince(mark) assert(calls[1].name == "Email/set" and calls[1].args.destroy[1] == "a" and calls[1].args.update == nil) mark = #requests sent = fastmail.sendMessage({to={{email="[email protected]"}}, subject="Hi", text="Body", from="[email protected]", attachments={{path="files/brief.pdf", mimeType="application/pdf"}}}) assert(sent.id == "d4" and sent.submissionId == "s4") calls = jmapSince(mark) assert(calls[1].name == "Mailbox/get" and calls[2].name == "Identity/get" and calls[3].upload) local upload = calls[3].upload assert(upload.method == "POST" and upload.url == "https://phl.api.fastmail.com/jmap/upload/u1/" ) assert(upload.body ~= nil and upload.headers["Content-Type"][1] == "application/pdf") draft = calls[4].args.create.draft assert(draft.from[1].email == "[email protected]" and draft.attachments[1].blobId == "blob1") assert(draft.attachments[1].name == "brief.pdf" and draft.attachments[1].disposition == "attachment") assert(draft.attachments[1].type == "application/pdf") assert(calls[5].args.create.send.identityId == "i-sup") assert(#responses == 0) end}fastmail_envelope_nulls_body_attachments_and_order.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req if string.find(req.url, "/jmap/download/", 1, true) then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(string.rep("x", 123))}) end assert(#responses > 0, "unexpected request: " .. req.url) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(if type(response)=="string" then response else json.encode(response))}) end} fs = fixture.files() local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" function session() return {username="[email protected]",primaryAccounts={[MAIL]="u1"},accounts={u1={name="Me"}}, capabilities={[MAIL]={},[SUB]={}},apiUrl="https://api.fastmail.com/jmap/api/", downloadUrl="https://phl-www.fastmailusercontent.com/jmap/download/{accountId}/{blobId}/{name}?type={type}"} end function result(name, args) return {methodResponses={{name,args,"0"}}} end folders={{id="in",role="inbox",name="Inbox"},{id="tr",role="trash"},{id="sp",role="junk"}, {id="dr",role="drafts"},{id="se",role="sent"}} function args(n) return json.decode(requests[n].body).methodCalls[1][2] end end, run=function(fastmail) local message=json.decode([[{"id":"m1","threadId":"t1","from":[{"name":null,"email":"[email protected]"}], "to":null,"cc":null,"bcc":null,"replyTo":null,"sentAt":"2026-09-01T12:00:00Z","messageId":["[email protected]"], "headers":[{"name":"Received","value":"by mail"}],"textBody":[{"partId":"p"}],"htmlBody":[], "bodyValues":{"p":{"value":"Hello","isTruncated":true}}, "attachments":[{"blobId":"b1","name":"file +.txt","type":"text/plain","size":123,"cid":null,"disposition":"attachment"}]}]]) responses={session(),result("Email/get",{list={{id="m2",preview="two"},message}}), result("Email/get",{list={message}})} local messages=fastmail.getMessages({{id="m1"},"m2"},{maxBodyValueBytes=1234}) local m=messages[1] assert(args(2).maxBodyValueBytes==1234) assert(m.id=="m1" and messages[2].id=="m2") assert(m.from=="[email protected]" and m.to=="" and m.body=="Hello" and m.bodyTruncated) assert(m.messageId=="[email protected]" and m.received[1]=="by mail") assert(m.attachments[1].id=="b1" and not m.attachments[1].inline and not m.attachments[1].contentId) -- Return a fresh provider object; connector decoration must not alter transport fixtures. responses[1]=result("Email/get",{list={json.decode([[{"id":"m1","attachments":[{"blobId":"b1","name":"file +.txt","type":"text/plain","size":123}]}]])}}) local downloaded=fastmail.getAttachment("m1","b1","mail/a.txt") assert(downloaded.size==123 and downloaded.url=="https://houston.test/mail/a.txt") local contents = fs.open("mail/a.txt", "r") assert(await(contents:readAll()) == string.rep("x", 123)) await(contents:close()) assert(requests[4].url=="https://phl-www.fastmailusercontent.com/jmap/download/u1/b1/file%20%2B.txt?type=text%2Fplain") for _, path in {false, "mail/dots.bin"} do local sent=#requests local ok, err = pcall(fastmail.getAttachment,"m1","..",path or nil) assert(not ok and err.code == "invalid_argument" and string.find(err.message, "blobId must be one", 1, true), tostring(err)) assert(#requests==sent,"a dot-segment blob ID must not reach Fastmail") end local before=#requests assert(not pcall(fastmail.getAttachment,"m/1","b1") and #requests==before,"an invalid message ID must not reach Fastmail") responses[1]=result("Email/get",{list={json.decode([[{"id":"m1","attachments":[{"blobId":"b2","name":"50% plan/v2.pdf","type":"application/pdf","size":123}]}]])}}) fastmail.getAttachment("m1","b2","mail/plan.pdf") assert(requests[#requests].url=="https://phl-www.fastmailusercontent.com/jmap/download/u1/b2/attachment?type=application%2Fpdf",requests[#requests].url) local ids={} for i=1,51 do ids[i]="m"..i end assert(not pcall(fastmail.getMessages,ids)) end}fastmail_filters_pagination_session_isolation_and_threads.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req if string.find(req.url, "/jmap/download/", 1, true) then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(string.rep("x", 123))}) end assert(#responses > 0, "unexpected request: " .. req.url) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(if type(response)=="string" then response else json.encode(response))}) end} fs = fixture.files() local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" function session() return {username="[email protected]",primaryAccounts={[MAIL]="u1"},accounts={u1={name="Me"}}, capabilities={[MAIL]={},[SUB]={}},apiUrl="https://api.fastmail.com/jmap/api/", downloadUrl="https://www.fastmailusercontent.com/jmap/download/{accountId}/{blobId}/{name}?type={type}"} end function result(name, args) return {methodResponses={{name,args,"0"}}} end folders={{id="in",role="inbox",name="Inbox"},{id="tr",role="trash"},{id="sp",role="junk"}, {id="dr",role="drafts"},{id="se",role="sent"}} function args(n) return json.decode(requests[n].body).methodCalls[1][2] end end, run=function(fastmail) responses={session(),result("Mailbox/get",{list=folders}),result("Email/query",{ids={"m2"},position=0,total=3}), result("Mailbox/get",{list=folders}),result("Email/query",{ids={"m1"},position=1,total=3}), result("Email/get",{list={{id="m1",threadId="t1"}}}),session()} local page=fastmail.listMessages({maxResults=2,folder="INBOX",after="2026-01-01",from={"a","b"},text="hello"}) assert(page.messages[1].id=="m2" and page.nextPageToken=="1") -- server returned fewer than requested local a=args(3) assert(a.accountId=="u1" and a.limit==2 and a.calculateTotal) local conditions=a.filter.conditions local seen={} for _,f in conditions do for k,v in f do seen[k]=v end end assert(seen.inMailbox=="in" and seen.after=="2026-01-01T00:00:00Z" and seen.text=="hello") assert(#conditions==5) local threads=fastmail.listThreads({pageToken=page.nextPageToken}) assert(threads.threads[1].id=="t1" and threads.nextPageToken=="2") a=args(5) assert(a.position==1 and a.collapseThreads) assert(#a.filter.conditions==2 and a.filter.conditions[1].operator=="NOT") fastmail.getProfile() assert(#requests==6, "session must be cached within one invocation") local ok,err=pcall(fastmail.listMessages,{pageToken="bad"}) assert(not ok and string.find(tostring(err),"pageToken",1,true)) assert(#requests==6) end}fastmail_partial_alias_scope.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "read"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req assert(#responses > 0, "unexpected request: " .. tostring(req.url)) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" function session() return {username="[email protected]", primaryAccounts={[MAIL]="u1"}, accounts={u1={name="Me"}}, capabilities={[MAIL]={}, [SUB]={}}, apiUrl="https://api.fastmail.com/jmap/api/"} end function result(name, args) return {methodResponses={{name, args, "0"}}} end end, run=function(fastmail) responses={session(), result("Identity/get", {list={{id="i", email="[email protected]", name="Me"}}})} local listed = fastmail.listAliases() assert(#listed.aliases == 1 and listed.aliases[1].canSend and not listed.aliases[1].masked) assert(#listed.notes == 1 and string.find(listed.notes[1], "Masked Email", 1, true)) assert(#requests == 2) assert(fastmail.replyMessage == nil and fastmail.deleteMessage == nil) end}fastmail_sends_and_trashes_with_confirmations.luau
return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "write"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req if string.find(req.url, "/jmap/download/", 1, true) then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(string.rep("x", 123))}) end assert(#responses > 0, "unexpected request: " .. req.url) local response = table.remove(responses, 1) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(if type(response)=="string" then response else json.encode(response))}) end} fs = fixture.files() local MAIL="urn:ietf:params:jmap:mail" local SUB="urn:ietf:params:jmap:submission" function session() return {username="[email protected]",primaryAccounts={[MAIL]="u1"},accounts={u1={name="Me"}}, capabilities={[MAIL]={},[SUB]={}},apiUrl="https://api.fastmail.com/jmap/api/", downloadUrl="https://www.fastmailusercontent.com/jmap/download/{accountId}/{blobId}/{name}?type={type}"} end function result(name, args) return {methodResponses={{name,args,"0"}}} end function results(...) local out = {} for index, item in {...} do out[index] = {item[1], item[2], tostring(index - 1)} end return {methodResponses=out} end folders={{id="in",role="inbox",name="Inbox"},{id="tr",role="trash"},{id="sp",role="junk"}, {id="dr",role="drafts"},{id="se",role="sent"}} function args(n) return json.decode(requests[n].body).methodCalls[1][2] end end, run=function(fastmail) responses={session(),results({"Mailbox/get",{list=folders}},{"Identity/get",{list={{id="i",email="[email protected]",name="Me"}}}}), result("Email/set",{created={draft={id="m"}}}), result("EmailSubmission/set",{created={send={id="s"}}}),result("Mailbox/get",{list=folders}), result("Email/set",json.decode([[{"updated":{"m":null},"notUpdated":null}]]))} local sent=fastmail.sendMessage({to={{email="[email protected]"}},subject="Hi",text="Body"}) assert(sent.id=="m" and sent.submissionId=="s") local reads=json.decode(requests[2].body) assert(#reads.methodCalls==2 and reads.methodCalls[1][1]=="Mailbox/get" and reads.methodCalls[2][1]=="Identity/get") assert(reads.methodCalls[2][3]=="1" and reads.using[3]=="urn:ietf:params:jmap:submission") assert(args(3).create.draft.mailboxIds.dr and args(3).create.draft.bodyValues.text.value=="Body") assert(args(3).create.draft.attachments == nil and args(3).create.draft.inReplyTo == nil) local a=args(4) assert(a.create.send.emailId=="m" and a.create.send.identityId=="i") assert(a.onSuccessUpdateEmail["#send"]["mailboxIds/se"] == true and a.onSuccessUpdateEmail["#send"].mailboxIds == nil) assert(string.find(requests[4].body, "\"mailboxIds/dr\":null", 1, true)) assert(string.find(requests[4].body, "\"keywords/$draft\":null", 1, true) and a.onSuccessUpdateEmail["#send"]["keywords/$seen"] == true and a.onSuccessUpdateEmail["#send"].keywords == nil) assert(fastmail.trashMessage("m").id=="m") assert(args(6).update.m.mailboxIds.tr and not args(6).update.m.mailboxIds.dr) end}manifest.luau
return { contract = function(m) do local r, err = m.resolve(nil, nil, { token = "fixture-token" }, "token") assert(not err, tostring(err)) local p = r.Proxy for _, host in { "api.fastmail.com", "phl.api.fastmail.com", "ams.api.fastmail.com", "jmap.fastmail.com" } do for _, route in { { "GET", "/jmap/session" }, { "POST", "/jmap/api/" }, { "POST", "/jmap/upload/u1/" }, { "GET", "/jmap/download/u1/blob/file" }, } do local recipe, err = m.recipe(p, route[1], "https://" .. host .. route[2], nil) assert(not err, tostring(err)) local h, err = m.prepare(recipe, r.Context, nil) if (err ~= nil) or (m.header(h, "Authorization") ~= "Bearer fixture-token") then m.fail("%s: %s %s", host, h, err) end end end for _, host in { "fastmailusercontent.com", "www.fastmailusercontent.com", "phl-www.fastmailusercontent.com", } do local recipe, err = m.recipe( p, "GET", "https://" .. host .. "/jmap/download/u1/blob/file?type=text%2Fplain", nil ) assert(not err, tostring(err)) local h, err = m.prepare(recipe, r.Context, nil) if (err ~= nil) or (m.header(h, "Authorization") ~= "Bearer fixture-token") then m.fail("%s: %s %s", host, h, err) end for _, route in { { "POST", "/jmap/api/" }, { "POST", "/jmap/upload/u1/" }, { "GET", "/other" } } do do local _, err = m.recipe(p, route[1], "https://" .. host .. route[2], nil) if err == nil then m.fail("download host accepted %s", route) end end end end for _, host in { "fastmail.com", "app.fastmail.com", "evilapi.fastmail.com", "api.fastmail.com.evil.test", "www.fastmailusercontent.com.evil.test", } do do local _, err = m.recipe(p, "GET", "https://" .. host .. "/jmap/download/u1/blob/file", nil) if err == nil then m.fail("accepted %s", host) end end end end end, }named_inputs_and_bounded_fetches.luau
return { scenario = {auth_method = "token", auth_config = {token = "fixture-private-token"}, config = {}, publisher = {}}, access = {data = "write"}, configure = function() requests, responses = {}, {} http = {request = function(request) requests[#requests + 1] = request if request.body then local invocation = json.decode(request.body).methodCalls[1] -- Cyrus _email_getargs_parse accepts maxBodyValueBytes only when > 0. -- https://github.com/cyrusimap/cyrus-imapd/blob/master/imap/jmap_mail.c if invocation[1] == "Email/get" and invocation[2].maxBodyValueBytes == 0 then return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode({ methodResponses = {{"error", {type = "invalidArguments", arguments = {"maxBodyValueBytes"}}, "0"}}, }))}) end end local response = table.remove(responses, 1) assert(response, "unexpected request: " .. request.url) if type(response) == "table" and response.failure then return fixture.operation({statusCode=response.failure, headers={}, body=fixture.reader(response.body)}) end return fixture.operation({statusCode=200, headers={}, body=fixture.reader(if type(response)=="string" then response else json.encode(response))}) end} fs = fixture.files() function result(name, data) return {methodResponses = {{name, data, "0"}}} end function args(index) return json.decode(requests[index].body).methodCalls[1][2] end responses[1] = { username = "[email protected]", primaryAccounts = {["urn:ietf:params:jmap:mail"] = "u1"}, accounts = {u1 = {name = "Me"}}, capabilities = {}, apiUrl = "https://api.fastmail.com/jmap/api/", downloadUrl = "https://www.fastmailusercontent.com/jmap/download/{accountId}/{blobId}/{name}?type={type}", } end, run = function(fastmail) responses[#responses + 1] = result("Email/query", {ids = {}, position = 0, total = 0}) local page = fastmail.listMessages({includeSpamTrash = true}) assert(#page.messages == 0 and page.nextPageToken == nil) assert(#requests == 2, "an unfiltered query does not need folder metadata") responses[1] = result("Email/get", {list = {{id = "m2", preview = "two"}, {id = "m1", preview = "one"}}}) local messages = fastmail.getMessages({ids = {{id = "m1"}, "m2"}, maxBodyValueBytes = 42}) assert(messages[1].id == "m1" and messages[2].id == "m2", "preserve caller order") assert(args(3).maxBodyValueBytes == 42) responses[1] = result("Email/get", {list = {{id = "m1", preview = "one"}}}) assert(fastmail.getMessage({id = "m1", maxBodyValueBytes = 7}).body == "one") assert(args(4).maxBodyValueBytes == 7) local ids, firstBatch = {}, {} for index = 1, 51 do ids[index] = "m" .. index end for index = 50, 1, -1 do firstBatch[#firstBatch + 1] = {id = ids[index]} end responses = { result("Thread/get", {list = {{id = "thread", emailIds = ids}}}), result("Email/get", {list = firstBatch}), result("Email/get", {list = {{id = "m51"}}}), } local thread = fastmail.getThread({id = "thread", maxBodyValueBytes = 12}) assert(#thread.messages == 51 and thread.messages[1].id == "m1" and thread.messages[51].id == "m51") assert(#args(6).ids == 50 and #args(7).ids == 1 and args(7).ids[1] == "m51") assert(args(6).maxBodyValueBytes == 12 and args(7).maxBodyValueBytes == 12) local attachment = {blobId = "blob", name = "a +.txt", type = "text/plain", size = 3} responses = {result("Email/get", {list = {{id = "m1", attachments = {attachment}}}}), string.char(0,255,120)} local files = fastmail.getAttachments({messageId = "m1", items = {{id = "blob", path = "mail/a.txt"}}}) assert(#files == 1 and files[1].path == "mail/a.txt" and files[1].size == 3) assert(files[1].url == "https://houston.test/mail/a.txt") local metadata = args(8) assert(metadata.fetchTextBodyValues == nil and metadata.fetchHTMLBodyValues == nil, "attachment lookup must not fetch message bodies") local properties = {} for _, name in metadata.properties do properties[name] = true end assert(properties.attachments and not properties.bodyValues and not properties.textBody and not properties.htmlBody) local downloaded = fs.open("mail/a.txt", "r") assert(await(downloaded:readAll()) == string.char(0,255,120)) await(downloaded:close()) assert(requests[9].url == "https://www.fastmailusercontent.com/jmap/download/u1/blob/a%20%2B.txt?type=text%2Fplain") local before = #requests assert(#fastmail.getAttachments({messageId = "m1", items = {}}) == 0) assert(#requests == before, "empty attachment selection needs no transport") responses = {result("Email/get", {list = {{id = "m1", attachments = {attachment}}}})} local ok, err = pcall(fastmail.getAttachments, {messageId = "m1", items = { {id = "blob", path = "same.txt"}, {id = "blob", path = "same.txt"}, }}) assert(not ok and string.find(tostring(err), "distinct", 1, true)) assert(#requests == before + 1, "validate every destination before downloading") responses = {result("Email/get", {list = {{id = "m1", attachments = {attachment}}}}), {failure = 503, body = "busy now"}} ok, err = pcall(fastmail.getAttachments, {messageId = "m1", items = {{id = "blob", path = "mail/b.txt"}}}) assert(not ok and string.find(tostring(err), "upstream HTTP 503 busy now", 1, true) and string.find(tostring(err), "\"retryable\":true", 1, true), tostring(err)) responses = { result("Mailbox/get", {list = {{id = "in", role = "inbox"}}}), result("Mailbox/set", {created = {folder = {id = "projects"}}}), } local folder = fastmail.createFolder({name = "Projects", parentId = "in"}) assert(folder.id == "projects" and folder.name == "Projects") local created = args(#requests).create.folder assert(created.name == "Projects" and created.parentId == "in") assert(#responses == 0) -- Preserve the public zero-means-unlimited API without sending an explicit zero. local fullBody = string.rep("x", 65537) for _, case in { {read = function() return fastmail.getMessage({id = "m1", maxBodyValueBytes = 0}) end}, {read = function() return fastmail.getMessage("m1", {maxBodyValueBytes = 0}) end}, {read = function() return fastmail.getMessages({ids = {"m1"}, maxBodyValueBytes = 0})[1] end}, {read = function() return fastmail.getMessages({"m1"}, {maxBodyValueBytes = 0})[1] end}, {thread = true, read = function() return fastmail.getThread({id = "thread", maxBodyValueBytes = 0}).messages[1] end}, {thread = true, read = function() return fastmail.getThread("thread", {maxBodyValueBytes = 0}).messages[1] end}, } do -- Both thread APIs first fetch the message IDs. responses = {result("Email/get", {list = {{id = "m1", textBody = {{partId = "1"}}, bodyValues = {["1"] = {value = fullBody, isTruncated = false}}}}})} if case.thread then table.insert(responses, 1, result("Thread/get", {list = {{id = "thread", emailIds = {"m1"}}}})) end local unbounded = case.read() local request = args(#requests) assert(request.maxBodyValueBytes == nil, "omit the cap to disable truncation on Fastmail") assert(request.ids[1] == "m1" and #request.ids == 1) assert(unbounded.body == fullBody and not unbounded.bodyTruncated) assert(#responses == 0) end end, }read_and_draft.luau
-- Draft connections prepare drafts but expose no send or other mail change. return {scenario={["auth_config"]={["token"]="fixture-private-password !@#"},["auth_method"]="token",["config"]={},["publisher"]={}},access = {data = "draft"}, configure=function() requests, responses = {}, {} http = {request = function(req) requests[#requests + 1] = req assert(#responses > 0, "unexpected request: " .. tostring(req.url)) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(table.remove(responses, 1)))}) end} local MAIL="urn:ietf:params:jmap:mail" function result(name, args) return {methodResponses={{name, args, "0"}}} end session={username="[email protected]", primaryAccounts={[MAIL]="u1"}, accounts={u1={name="Me"}}, capabilities={[MAIL]={}}, apiUrl="https://api.fastmail.com/jmap/api/"} folders={{id="dr", role="drafts", name="Drafts"}} end, run=function(fastmail) for _, name in {"createDraft", "createReplyDraft", "updateDraft", "deleteDraft", "listMessages", "getMessage"} do assert(type(fastmail[name]) == "function", "Draft access must export " .. name) end for _, name in {"sendDraft", "sendMessage", "replyMessage", "deleteMessage", "destroyMessage", "moveMessages", "archiveMessages", "createFolder", "markRead"} do assert(fastmail[name] == nil, "Draft access must omit " .. name) end responses={session, result("Mailbox/get", {list=folders}), result("Email/set", {created={draft={id="d1"}}}), result("Email/get", {list={{id="d1", keywords={["$draft"]=true}}}}), result("Email/set", {destroyed={"d1"}})} assert(fastmail.createDraft({to={{email="[email protected]"}}, subject="Hi", text="Body"}).id == "d1") local draft = json.decode(requests[3].body).methodCalls[1][2].create.draft assert(draft.mailboxIds.dr and draft.keywords["$draft"] and draft.to[1].email == "[email protected]") assert(fastmail.deleteDraft("d1").id == "d1") assert(json.decode(requests[5].body).methodCalls[1][2].destroy[1] == "d1" and #responses == 0) end}read_state.luau
return { scenario = {auth_method = "token", auth_config = {token = "fixture-private-password !@#"}, config = {}, publisher = {}}, access = {data = "write"}, configure = function() requests, responses = {}, {} local MAIL = "urn:ietf:params:jmap:mail" local state = { username = "[email protected]", primaryAccounts = {[MAIL] = "u1"}, accounts = {u1 = {name = "Me"}}, capabilities = {[MAIL] = {}}, apiUrl = "https://api.fastmail.com/jmap/api/", } http = {request = function(req) requests[#requests + 1] = req assert(req.headers.Authorization == nil) if req.method == "GET" then assert(#requests == 1 and req.url == "https://api.fastmail.com/jmap/session") return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode(state))}) end assert(req.method == "POST" and req.url == state.apiUrl) local body = json.decode(req.body) assert(#body.using == 2 and body.using[2] == MAIL, "read state requires no submission scope") assert(#body.methodCalls == 1 and body.methodCalls[1][1] == "Email/set") assert(body.methodCalls[1][2].accountId == "u1") assert(#responses > 0, "unexpected write") local response = table.remove(responses, 1) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode({ methodResponses = {{"Email/set", response, "0"}}, }))}) end} function update(n) return json.decode(requests[n].body).methodCalls[1][2].update end function checkPatch(patch, value) local count = 0 for key, actual in patch do count += 1 assert(key == "keywords/$seen" and actual == value, "patch must preserve other keywords and mailboxes") end assert(count == 1) end end, run = function(mail) for _, fn in {mail.markRead, mail.markUnread} do for _, invalid in {"", {}, {id = ""}, {"valid", ""}} do assert(not pcall(fn, invalid)) end end assert(#requests == 0, "validate every ID before discovery or mutation") responses = {json.decode([[{"updated":{"m":null}}]])} local marked = mail.markRead("m") assert(#marked.ids == 1 and marked.ids[1] == "m") checkPatch(update(2).m, true) responses = {json.decode([[{"updated":{"m":null}}]])} local unread = mail.markUnread({id = "m"}) assert(#unread.ids == 1 and unread.ids[1] == "m") checkPatch(update(3).m, json.decode("null")) local ids, first = {}, {} for i = 1, 51 do ids[i] = {id = "m" .. i} if i <= 50 then first["m" .. i] = json.decode("null") end end responses = {{updated = first}, {updated = {m51 = {}}}} marked = mail.markRead(ids) assert(#marked.ids == 51 and #requests == 5) for batch, request in {update(4), update(5)} do local count = 0 for id, patch in request do count += 1 checkPatch(patch, true) local index = tonumber(string.sub(id, 2)) assert(if batch == 1 then index <= 50 else index == 51) end assert(count == (if batch == 1 then 50 else 1)) end for i, id in marked.ids do assert(id == "m" .. i) end for i = 52, 101 do ids[i] = {id = "m" .. i} end responses = {{updated = first}, {notUpdated = {m51 = {type = "forbidden", description = "read-only mailbox"}}}} local ok, err = pcall(mail.markUnread, ids) assert(not ok and string.find(tostring(err), "m51: forbidden", 1, true)) assert(string.find(tostring(err), '"operation":"markUnread"', 1, true)) assert(#requests == 7 and #responses == 0, "partial failure must stop before batch 3 without replay") for _, request in {update(6), update(7)} do for _, patch in request do checkPatch(patch, json.decode("null")) end end responses = {{updated = {}}} ok, err = pcall(mail.markRead, {"missing"}) assert(not ok and string.find(tostring(err), "Missing update confirmation for missing", 1, true)) responses = {{notUpdated = {missing = {type = "notFound"}}}} ok, err = pcall(mail.markRead, "missing") assert(not ok and string.find(tostring(err), "missing: notFound", 1, true)) assert(#requests == 9 and #responses == 0) end, }write_batches_and_confirmations.luau
return { scenario = {auth_method = "token", auth_config = {token = "fixture-private-token"}, config = {}, publisher = {}}, access = {data = "write"}, configure = function() requests, responses = {}, {} http = {request = function(request) requests[#requests + 1] = request local response = table.remove(responses, 1) assert(response, "unexpected request: " .. request.url) return fixture.operation({statusCode=200, headers={}, body=fixture.reader(json.encode(response))}) end} function result(name, data) return {methodResponses = {{name, data, "0"}}} end -- One request carrying several method calls, answered in order. function results(...) local out = {} for index, item in {...} do out[index] = {item[1], item[2], tostring(index - 1)} end return {methodResponses = out} end function args(index) return json.decode(requests[index].body).methodCalls[1][2] end folders = {{id = "ar", role = "archive"}, {id = "dr", role = "drafts"}, {id = "se", role = "sent"}} responses[1] = { username = "[email protected]", primaryAccounts = {["urn:ietf:params:jmap:mail"] = "u1"}, accounts = {u1 = {name = "Me"}}, capabilities = {["urn:ietf:params:jmap:submission"] = {}}, apiUrl = "https://api.fastmail.com/jmap/api/", } end, run = function(fastmail) local ids, updated = {}, {} for index = 1, 51 do ids[index] = "m" .. index if index <= 50 then updated[ids[index]] = json.decode("null") end end responses[#responses + 1] = result("Mailbox/get", {list = folders}) responses[#responses + 1] = result("Email/set", {updated = updated}) responses[#responses + 1] = result("Email/set", {updated = {m51 = json.decode("null")}}) local moved = fastmail.moveMessages({ids = ids, folder = "archive"}) assert(#moved.ids == 51 and moved.ids[1] == "m1" and moved.ids[51] == "m51" and moved.folderId == "ar") local first, second = args(3).update, args(4).update assert(first.m1.mailboxIds.ar and first.m50.mailboxIds.ar and first.m51 == nil) assert(second.m51.mailboxIds.ar and second.m50 == nil) local destroyed = {} for index = 1, 50 do destroyed[index] = ids[index] end responses = {result("Email/set", {destroyed = destroyed}), result("Email/set", {destroyed = {}})} local before = #requests local ok, err = pcall(fastmail.destroyMessages, ids) assert(not ok and string.find(tostring(err), "Missing destroy confirmation for m51", 1, true)) assert(#requests == before + 2, "a partial destructive batch must never replay") assert(#args(before + 1).destroy == 50 and args(before + 2).destroy[1] == "m51") local identities = {list = {{id = "me", email = "[email protected]"}}} responses = { results({"Mailbox/get", {list = folders}}, {"Identity/get", identities}), result("Email/set", {created = {draft = {id = "draft"}}}), result("EmailSubmission/set", {created = {send = {}}}), } before = #requests ok, err = pcall(fastmail.sendMessage, {to = {{email = "[email protected]"}}, text = "Hello"}) assert(not ok and string.find(tostring(err), "Missing submission confirmation", 1, true)) assert(#requests == before + 3, "an ambiguous send must never replay") responses = { results({"Mailbox/get", {list = folders}}, {"Identity/get", identities}), result("Email/set", {created = {draft = {id = ""}}}), } before = #requests ok, err = pcall(fastmail.sendMessage, {to = {{email = "[email protected]"}}, text = "Hello"}) assert(not ok and string.find(tostring(err), "Missing draft creation confirmation", 1, true)) assert(#requests == before + 2, "invalid draft IDs must never be submitted") assert(#responses == 0) end, }