# Mailbox Connector API > One HTTP API to send mail, prepare drafts and read and process incoming mail in a Microsoft 365 or Google mailbox. This file is the complete documentation, for developers and for AI assistants. The code samples are in cURL; every sample has been run against a test server. Address of the API: https://mailboxconnector.com. Description of every call in OpenAPI format: https://mailboxconnector.com/openapi.json. This documentation with samples in another language: https://mailboxconnector.com/llms-full.txt (cURL), https://mailboxconnector.com/llms-csharp.txt (C#), https://mailboxconnector.com/llms-java.txt (Java), https://mailboxconnector.com/llms-php.txt (PHP), https://mailboxconnector.com/llms-python.txt (Python), https://mailboxconnector.com/llms-node.txt (Node.js), https://mailboxconnector.com/llms-go.txt (Go). ## Rules for a client - Logging in takes three steps: fetch the challenge, read the matching line from the key file, exchange it for a token. The details are under "Logging in". - Reuse the token until a minute before it expires (it is valid for 10 minutes). Never log in for every call. - Let only one login run at a time per process. - The challenge is a counter that every login attempt with the right security key moves on. On a 401 while logging in: wait a random 0.2 to 1 second, fetch a new challenge, try again, three attempts at most. - More than five wrong codes lock the application for 5 minutes (403). Then stop and wait. - Read the key file without loading it into memory; it has 1,000,000 lines. - Operations answer HTTP 200 with a `status` field. Always check `status`; 0 is success. - Choices are numbers, not names. Field names are camelCase. Dates of a mail are wall-clock time of the sender without a time zone. - Never put the security key or the contents of the key file in source code, and never ask the user to paste them into a chat. ## Mailbox Connector SDK Send mail, prepare drafts and read and process incoming mail from your customer's mailbox, through one HTTP API for Microsoft 365 and Google. > **Your keys are passwords.** Together, the security key and the key file give access to every mailbox that is connected to your application. Keep them out of your source code and let only your own server read them. ### How it works 1. **Log in.** Your application logs in with its application id, its security key and a code from the key file. It receives a token that is valid for 10 minutes. See Logging in. 2. **Connect a mailbox.** The owner of the mailbox gives permission once, at Microsoft or Google. See Connecting a mailbox. 3. **Call operations.** With the token you send, read and move mail in that mailbox. ### What you need You find all three with your application in Mailbox Connector. - `application id`: The id of your application, for example `3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70`. - `security key`: A secret key that belongs to the application. - `security.mckey`: The key file: 1,000,000 lines with codes. You download it as `{application id}.mckey`; this documentation calls it `security.mckey`. ### Conventions - The address of the API is `https://mailboxconnector.com`. - Requests and responses are JSON, with field names in camelCase. - Every call after logging in sends the token in the header `Authorization: Bearer …`. - Choices are numbers. Every field lists which number means what. - An attachment is base64 in a JSON string. - Dates are ISO 8601. For a mail that is the wall-clock time of the sender, without a time zone; see Reading mail. ### The samples Pick your language at the top of a code block. The choice applies to all blocks and is remembered. The samples on the following pages use these settings: ```bash BASE_URL="https://mailboxconnector.com" APPLICATION_ID="3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70" SECURITY_KEY="your-security-key" # from a secret store, never from source control KEY_FILE="/etc/mailboxconnector/security.mckey" ``` - `cURL`: Bash with `curl` and `jq`. - `C#`: .NET 6 or newer, without extra packages. - `Java`: Java 17 or newer, with Jackson for JSON. - `PHP`: PHP 8.1 or newer, with the cURL extension. - `Python`: Python 3.8 or newer, with `requests`. - `Node.js`: Node.js 18 or newer, without extra packages. - `Go`: Go 1.20 or newer, standard library only. ## Logging in Logging in takes three steps: you fetch a challenge, look up the matching code in your key file and exchange that code for a token. > **One application is one connection.** An application in Mailbox Connector is meant for one installation of your software: a site, with at most a few batches next to it. When more processes log in at the same time, they get in each other's way. After more than five wrong codes the application is locked for 5 minutes. Read Limits and retrying before you let more than one process log in. ### Step 1: fetch the challenge `GET /api/login/{applicationId}` The response is a number from 0 up to and including 999,999. ```json { "challenge": 418273 } ``` ```bash # Needs curl and jq. CHALLENGE=$(curl -fsS "$BASE_URL/api/login/$APPLICATION_ID" | jq -r '.challenge') ``` - `200` Success: The response holds the challenge. - `204` No key file: No key file has been created for this application yet. Try again in a few minutes. - `401` Unknown: There is no application with this id. ### Step 2: look up the code The challenge is a line number in your key file, counted from 0. So challenge 0 is the first line: you skip as many lines as the challenge says and read the next one. ```text challenge 0 -> line 1: Xk29fLq8 challenge 1 -> line 2: b7TmR0zQp1 challenge 2 -> line 3: 9aWd3E ... challenge 418273 -> line 418274: mP4tY8sKx2 ... challenge 999999 -> line 1000000: Hq5nV2x8Lr0T ``` ```bash # Skip $CHALLENGE lines and read the next one: challenge 0 is the first line of the file. CODE=$(read_code "$KEY_FILE" "$CHALLENGE") ``` The function that reads the line without loading the whole file is on Reading the key file. ### Step 3: log in `POST /api/login` - `code` (string, required): The line from the key file that belongs to the challenge. - `applicationId` (string, required): The id of your application. - `securityKey` (string, required): The security key of your application. ```bash # curl -f fails on 401 (wrong code, counts towards the lock) and on 403 (locked for 5 minutes) LOGIN=$(curl -fsS -X POST "$BASE_URL/api/login" \ -H "Content-Type: application/json" \ -d "$(jq -n --arg code "$CODE" --arg app "$APPLICATION_ID" --arg key "$SECURITY_KEY" \ '{code: $code, applicationId: $app, securityKey: $key}')") TOKEN=$(jq -r '.bearer' <<<"$LOGIN") VALID_UNTIL=$(( $(date +%s) + $(jq -r '.validMinutes' <<<"$LOGIN") * 60 )) ``` #### Response ```json { "validMinutes": 10, "bearer": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNmMmI4YzFlLTdhNGQ…" } ``` - `bearer` (string): The token for all following calls. - `validMinutes` (int): How long the token is valid: 10 minutes. - `200` Logged in: The response holds the token. Earlier failures are cleared by this. - `401` Refused: The code or the security key is wrong, or the application does not exist. This counts as a failure. Fetch a new challenge before you try again. - `403` Locked: There were more than five failures. Wait 5 minutes. ### Using the token Send the token with every call: ```http POST /api/operation/sendmail HTTP/1.1 Host: mailboxconnector.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNmMmI4YzFlLTdhNGQ… Content-Type: application/json ``` - Keep the token and reuse it until a minute before it expires. Do not log in again for every call. - The token holds the permissions your application had at the moment of logging in. Permissions that are added because a mailbox gets connected apply from the next login. - The complete client does all of this for you. ## Reading the key file The key file is about 10 MB. For every login you need exactly one line of it. Read that line without loading the whole file into memory. ### The file - `lines`: 1,000,000, one code per line. - `code`: 6 to 12 characters: letters and digits. - `line ending`: A line feed (`\n`), after the last line as well. - `encoding`: ASCII, without a BOM. ### Finding the line The lines are not equally long, so you cannot jump to a fixed position. The economical way is: read the file in blocks into one buffer, count the line endings, and turn only the requested line into a string. ```bash # Prints line $2 (zero-based) of key file $1. # sed reads the file as a stream and quits right after the requested line, # so memory use does not depend on the size of the file. read_code() { sed -n "$(( $2 + 1 )){p;q}" "$1" | tr -d '\r' } ``` > **What it saves.** This function uses one 64 KB buffer, whichever line you ask for. Reading the whole file and splitting it into lines costs 40 to 70 MB per login. ### Better not - **Reading the whole file**, for example with `File.ReadAllLines`, `file()`, `readlines()` or `readFileSync().split()`. - **Putting the file in your repository.** It is a secret. Git can also convert the line endings; that is why the samples strip a possible `\r` from the line. - **Keeping the contents in memory** to make it faster. You read one line every ten minutes; it does not need to be faster, and this way the secret stays on disk. ## Limits and retrying The challenge is a counter. Once you know how it works, you also know why two processes can disturb each other and how to deal with that. ### How the challenge works - Every application has one counter. Fetching the challenge returns its current value and changes nothing. - Every login attempt with the right security key moves the counter one up, whether the code was right or wrong. An attempt with a wrong security key changes nothing. - So two processes that fetch a challenge at the same moment get the same number. The first one to log in succeeds. The second one gets a 401, because the counter has moved on by then. ### The lock - `401` Wrong code: Counts as one failure for the application, whichever address it comes from. - `401` Wrong security key: Counts as one failure for the address it comes from. It does not lock the application. - `403` More than 5 failures: Logging in is locked until 5 minutes after the last failure. Wrong codes lock the application; wrong security keys lock only the address they came from. - `200` Successful login: Clears the failures of the application. So as long as someone succeeds in between, the count does not build up. ### What your client must do 1. **Reuse the token.** It is valid for 10 minutes. Only log in again when it expires within a minute. 2. **One login at a time per process.** Let simultaneous calls wait for the same login instead of each logging in themselves. 3. **On a 401: wait a moment and start over.** Wait a random time between 0.2 and 1 second, fetch a new challenge and log in again. Stop after three attempts. 4. **On a 403: stop.** Wait 5 minutes. Trying again does not help. 5. **Share the token where you can.** Processes on the same server can share one token; then only one of them logs in. The PHP client does that with a file. The complete client follows these rules. ### How many processes When several processes log in at the same moment, one succeeds and the others get a 401. With a site and three batches that stays well below the limit. Four batches is possible, but leave it at that: with more processes you risk that together they make more than five failures in a row, and then the application is locked for 5 minutes. > **Spread your batches.** Do not start all batches at the same moment. A batch that starts at :00 and one that starts at :02 do not meet each other while logging in. ## Complete client One file per language that logs in, reuses the token, handles collisions and calls operations. Copy it and fill in your own settings. ```bash #!/usr/bin/env bash # Mailbox Connector login for shell scripts. Needs curl and jq. set -euo pipefail BASE_URL="https://mailboxconnector.com" APPLICATION_ID="3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70" SECURITY_KEY="your-security-key" KEY_FILE="/etc/mailboxconnector/security.mckey" MAX_LOGIN_ATTEMPTS=3 # every 401 counts towards the lock, so keep this low TOKEN="" TOKEN_VALID_UNTIL=0 # Prints line $2 (zero-based) of key file $1. # sed reads the file as a stream and quits right after the requested line, # so memory use does not depend on the size of the file. read_code() { sed -n "$(( $2 + 1 )){p;q}" "$1" | tr -d '\r' } # Logs in when there is no token yet or when it expires within a minute. # Call it in the script itself, not inside $( ... ): a subshell cannot hand TOKEN back. mc_login() { (( $(date +%s) < TOKEN_VALID_UNTIL - 60 )) && return 0 local attempt challenge code response status body for (( attempt = 1; attempt <= MAX_LOGIN_ATTEMPTS; attempt++ )); do # Step 1: ask for a challenge. challenge=$(curl -fsS "$BASE_URL/api/login/$APPLICATION_ID" | jq -r '.challenge') # Step 2: look up the matching line in the key file. code=$(read_code "$KEY_FILE" "$challenge") # Step 3: exchange the code for a JWT. response=$(curl -sS -w '\n%{http_code}' -X POST "$BASE_URL/api/login" \ -H "Content-Type: application/json" \ -d "$(jq -n --arg code "$code" --arg app "$APPLICATION_ID" --arg key "$SECURITY_KEY" \ '{code: $code, applicationId: $app, securityKey: $key}')") status=${response##*$'\n'} body=${response%$'\n'*} case "$status" in 200) TOKEN=$(jq -r '.bearer' <<<"$body") TOKEN_VALID_UNTIL=$(( $(date +%s) + $(jq -r '.validMinutes' <<<"$body") * 60 )) return 0 ;; 401) # Most likely another process logged in between our two calls, which moves the # challenge on. Wait a random moment so the two do not collide again, then # start over with a new challenge. sleep "0.$(( RANDOM % 8 + 2 ))" ;; 403) echo "Locked after too many wrong codes. Wait 5 minutes before logging in again." >&2 return 1 ;; *) echo "Login failed with HTTP $status" >&2 return 1 ;; esac done echo "Login failed after $MAX_LOGIN_ATTEMPTS attempts" >&2 return 1 } ``` ### Usage The samples with the operations assume this `client`: ```bash # Call mc_login before a request: it only logs in when the token is missing or about to expire. mc_login ``` ### Per language - `cURL`: Call `mc_login` before a request, in the script itself and not inside `$( … )`. The function only logs in when the token is missing or about to expire. - `C#`: Register the client as a singleton, so that all calls in the process use the same token. - `Java`: Create one instance and share it. `post` returns a Jackson `JsonNode`. - `PHP`: PHP starts every request with empty memory. That is why the client keeps the token in a file in the temporary folder, with a lock. This way all PHP processes on the server share one token. - `Python`: Create one instance and share it. The client is safe for multiple threads. - `Node.js`: Create one instance and share it. Simultaneous calls wait for the same login. - `Go`: Create one `Client` and share it; it is safe for multiple goroutines. `Post` fills the result you pass in. ## Connecting a mailbox Before your application can use a mailbox, its owner gives permission once, at Microsoft or Google. You start that with a connection request. ### The flow 1. Check whether the mailbox is connected already. 2. If not: create a connection request. You get an `id` back. 3. Send the user to `https://mailboxconnector.com/connect/{id}`. 4. There the user signs in at Microsoft or Google, as the mailbox itself, and gives permission. 5. After that the user returns to your `returnUrl`. Then check again whether the mailbox is connected. ### Checking the connection `POST /api/connectionrequest/check` (free) - `desiredEmailAddress` (string, required): The address of the mailbox. - `needsSendMail` (bool): You want to send mail. - `needsCreateDraft` (bool): You want to create drafts. - `needsReadMail` (bool): You want to read mail, get attachments and check folders. - `needsMoveMail` (bool): You want to move mails and set the read status. ```bash curl -fsS -X POST "$BASE_URL/api/connectionrequest/check" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d @- <<'JSON' { "logoUrl": "https://www.example.com/logo.png", "desiredEmailAddress": "info@example.com", "needsSendMail": true, "needsCreateDraft": false, "needsReadMail": true, "needsMoveMail": true } JSON ``` #### Response ```json { "connectionStatus": 2 } ``` The values of `connectionStatus`: - `0` NotConfigured: The mailbox is not connected to your application. Create a connection request. - `1` MissingPermissions: The mailbox is connected, but not for everything you ask. Create a new connection request with the permissions you need. - `2` Connected: The mailbox is connected with all requested permissions. ### Creating a connection request `POST /api/connectionrequest/create` (free) The same fields as for checking, plus: - `returnUrl` (string, required): The page in your application the user returns to after connecting. - `logoUrl` (string): The logo of your application, for the connect page. ```bash REQUEST_ID=$(curl -fsS -X POST "$BASE_URL/api/connectionrequest/create" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d @- <<'JSON' | jq -r '.id' { "returnUrl": "https://www.example.com/settings/mailbox", "logoUrl": "https://www.example.com/logo.png", "desiredEmailAddress": "info@example.com", "needsSendMail": true, "needsCreateDraft": false, "needsReadMail": true, "needsMoveMail": true } JSON ) # Send the user to this page to connect the mailbox; afterwards they return to your returnUrl. echo "$BASE_URL/connect/$REQUEST_ID" ``` #### Response ```json { "status": 0, "error": null, "id": "9d1c6f0a-52b7-4e1d-8a3f-6b2e0c4d7f19" } ``` - `id` (string): The id of the connection request. With it you send the user to the connect page. ### Good to know - **A connection request is valid for 30 minutes.** Create it at the moment the user is going to connect, not in advance. - **The user signs in as the mailbox itself.** When they sign in with another account, nothing is connected and they can try again. - **Does an administrator have to give permission?** Then the administrator signs in first and gives permission on behalf of the organisation. After that the user signs in, with the same connection request or a new one. - **Microsoft 365 or Google** is determined from the address. You do not have to specify it. - **New permissions apply from the next login** of your application. The token you already had does not know them yet. ## Sending mail Sends a mail from a connected mailbox. The mail also ends up in the sent items of that mailbox, unless you set `saveToSentItems` to `false`. `POST /api/operation/sendmail` (1 action) ### Request - `sender` (EmailAddress, required): The connected mailbox you send from. - `to` (EmailAddress[], required): The recipients. - `cc` (EmailAddress[]): Recipients in copy. - `bcc` (EmailAddress[]): Recipients in blind copy. - `subject` (string): The subject. - `body` (string): The content, as HTML. - `attachments` (MailAttachment[]): The attachments. - `saveToSentItems` (boolean): Whether a copy is kept in the sent items of the sending mailbox. Leave it out or set `true` to keep it (the default); `false` for mails nobody needs to find back there, such as login codes. Only for sending, not for drafts. #### EmailAddress - `email` (string, required): The e-mail address. - `alias` (string): The name the recipient sees. When you leave it out, the part before the at sign is used. #### MailAttachment - `filename` (string, required): The file name. - `contentType` (string, required): The type, for example `application/pdf`. - `data` (string, required): The contents of the file, as base64. - `contentId` (string): Leave empty for a regular attachment. When you fill it, the image is shown inside the text of the mail. See *Images inside the text* below. ```bash # base64 -w0 = base64 on one line (on macOS: base64 -i factuur-2026-0042.pdf) curl -fsS -X POST "$BASE_URL/api/operation/sendmail" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d @- <Beste Jan,

In de bijlage vind je de factuur.

", "attachments": [ { "filename": "factuur-2026-0042.pdf", "contentType": "application/pdf", "data": "$(base64 -w0 factuur-2026-0042.pdf)" } ] } JSON ``` ### Images inside the text An image that has to appear inside the text of the mail, such as a logo or a screenshot, is sent along as an attachment with a `contentId`. In the `body` you point to it with `cid:` and that id. ```json { "sender": { "email": "info@example.com", "alias": "Example BV" }, "to": [ { "email": "jan@example.org", "alias": "Jan Jansen" } ], "subject": "Je bestelling is onderweg", "body": "

Beste Jan,

Je bestelling is onderweg.

\"Example", "attachments": [ { "filename": "logo.png", "contentType": "image/png", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "contentId": "logo" } ] } ``` - You choose the id yourself, for example `logo` or `image1`. Use letters, digits, dots and hyphens, and every id once per mail. - The id in `contentId` and the id after `cid:` have to be the same. - An image with a `contentId` that the text does not point to is sent as a regular attachment. - Regular attachments and images inside the text can go together in one mail. - It works the same way with Creating a draft. > **Sending back an image from a mail you read.** Are you replying to a mail and do you want to include the images from that mail? In the `text` of a message, the place of every image holds ``; those images are in `inlineImages`. Get the contents with Getting an attachment, send the image along with a `contentId` of your own, and put `` with that id at that place in your new text. ### Response ```json { "status": 0, "error": null, "messageId": null, "retryAfterSeconds": null } ``` - `status` (int): `0` is success. See Statuses and errors. - `error` (string): The reason when it failed, otherwise `null`. - `messageId` (string): Not filled when sending. With Creating a draft this holds the id of the draft. - `retryAfterSeconds` (int): Only with the error `RateLimited` from our own limits: after how many seconds the mail can be sent. Also in the HTTP header `Retry-After`. ### Limits and the spam check Mailbox Connector stops an application that sends too much, or sends what looks like spam, before Microsoft or Google block the mailbox. The check runs entirely on our own servers: the content of a mail is only looked at in memory while it is sent, and never stored. **Limits per mailbox** (over all applications that send with that mailbox): - `20` per minute - `300` per hour - `1,500` per 24 hours **Limits per application:** `5,000` mails per 24 hours over all its mailboxes, and at most `100` recipients (`to`, `cc` and `bcc` together) per mail. - **New applications** start at half these limits for their first 7 days. - **Above a limit** the mail is not sent: `status` is `1`, `error` is `RateLimited`, and `retryAfterSeconds` says after how many seconds it fits again. The same number is in the HTTP header `Retry-After`. Wait that long and send the mail again; sending earlier is refused the same way. The mail provider can also answer `RateLimited`; then wait a minute. - **Larger runs**, such as invoices around the 1st of the month: contact us. We can raise the limits of your application. > **Large runs, such as invoices around the 1st.** The spam check learns the rhythm of your application: from the second month on, a run like the previous one is normal, also to the same customers. The very first run of a new application can be flagged for us to look at, but is not refused for its size alone. The limits do apply: 1,000 invoices from one mailbox take more than 3 hours at 300 an hour. So queue the mails instead of sending them in one loop, and on `RateLimited` put the mail back with "not before" = now + `retryAfterSeconds` rather than letting the whole run wait. Need more? Ask us beforehand to raise the limits of your application. **The spam check** gives every mail a score from its content (typical spam and phishing phrases in Dutch, English, German and French), its structure (links that show another address than where they go, shortened links, links to an IP address, dangerous attachments such as `.exe`) and the sending pattern of your application compared to its own normal, including monthly and yearly runs. - A mail that only looks a little suspicious is sent and marked for us to look at. - A mail that is clearly suspicious is refused with `SuspectedSpam`. The content of the mail and the sending pattern both have to be suspicious for that; one of the two alone never refuses a mail. - After 3 refusals within 24 hours sending is paused for the application: every mail gets `SendingPaused` until we have looked at it with you and lifted the pause. Reading and moving mail keep working. ## Creating a draft Prepares a mail in the drafts of a connected mailbox, without sending it. Useful when a person still adds something: your application prepares the quote, the salesperson writes a covering note and sends it. `POST /api/operation/createdraft` (1 action) ### Request Exactly the same fields as for Sending mail. ```bash curl -fsS -X POST "$BASE_URL/api/operation/createdraft" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d @- <<'JSON' { "sender": { "email": "info@example.com", "alias": "Example BV" }, "to": [ { "email": "jan@example.org", "alias": "Jan Jansen" } ], "cc": [], "bcc": [], "subject": "Offerte 2026-0107", "body": "

Beste Jan,

Hierbij onze offerte.

", "attachments": [] } JSON ``` ### Response ```json { "status": 0, "error": null, "messageId": "AAMkAGI2NGVhZTVlLTI1OGMtNDI4My1iZmE5…" } ``` - `status` (int): `0` is success. See Statuses and errors. - `error` (string): The reason when it failed, otherwise `null`. - `messageId` (string): The id of the draft in the mailbox. ## Reading mail Reads mails from the inbox or from a folder of a connected mailbox: one mail by id, or up to 250 mails per call, with or without filters. `POST /api/operation/readmails` (1 action) ### Request - `emailAddress` (string, required): The connected mailbox. - `path` (string[]): The folder. Without a path you read the inbox. See *Folders* further down. - `skip` (int): How many mails you skip. 0 by default. - `take` (int, required): How many mails you want: 1 up to and including 250. A higher number becomes 250. When you leave the field out, you get 1 mail. - `mailSort` (int, required): `1` is newest first, `0` is oldest first. Always send the field: without it you get oldest first. See *Sorting and paging*. - `filterUniqueId` (string): The `uniqueId` of one mail. You get exactly that mail; the path and the other filters are then ignored. - `filterIsRead` (bool): `false` for unread mails only, `true` for read mails only. - `filterReceived` (DateFilter): On the day of receipt. - `filterSender` (StringFilter): On the e-mail address of the sender. - `filterTo` (StringFilter): On the address of a recipient. One matching recipient is enough. `filterCc` and `filterBcc` work the same way. - `filterSubject` (StringFilter): On the subject. - `filterBody` (StringFilter): On the content. The comparison is made with the raw HTML. - `filterAttachmentFilenames` (StringFilter[]): On file names of attachments. For every filter in the list the mail must have a matching attachment. - `conversationId` (StringFilter): On the conversation the mail belongs to. With `filter` 0 you get all mails of one conversation. All filters you send must match. Text is compared without distinguishing upper and lower case. #### StringFilter - `filter` (int): `0` equals, `1` starts with, `2` ends with. - `value` (string): The text to compare with. #### DateFilter - `filter` (int): `1` is on that day, `2` is before that day, `3` is after that day. With 2 and 3 the day itself is not included. - `value` (string): The day, as `2026-10-01`. Do not send a time or a time zone. It is the day as you see it in `received`. ```bash # mailSort 1 = NewToOld; filterReceived 3 = After (from 1 October on); # filterSubject 1 = StartsWith; filterAttachmentFilenames 2 = EndsWith curl -fsS -X POST "$BASE_URL/api/operation/readmails" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d @- <<'JSON' { "emailAddress": "info@example.com", "skip": 0, "take": 50, "mailSort": 1, "filterIsRead": false, "filterReceived": { "filter": 3, "value": "2026-09-30" }, "filterSubject": { "filter": 1, "value": "Factuur" }, "filterAttachmentFilenames": [ { "filter": 2, "value": ".pdf" } ] } JSON ``` ### Response ```json { "status": 0, "error": null, "emails": [ { "uniqueId": "AAMkAGI2NGVhZTVlLTI1OGMtNDI4My1iZmE5…", "conversationId": "AAQkAGI2NGVhZTVlLTI1OGMtNDI4My1iZmE5…", "path": null, "received": "2026-09-30T16:56:22", "sender": { "email": "piet@example.org", "alias": "Piet de Vries" }, "to": [ { "email": "info@example.com", "alias": "Example BV" } ], "cc": [], "bcc": [], "subject": "RE: Offerte 2026-0107", "body": "

Hoi Jan,

Akkoord, zie de bijlage.

…", "isRead": false, "attachments": [ { "id": "AAMkATT1…", "filename": "offerte-getekend.pdf", "contentType": "application/pdf", "contentId": null }, { "id": "AAMkATT2…", "filename": "image001.png", "contentType": "image/png", "contentId": "image001.png@01DD50FC.95EE0E50" } ], "messages": [ { "date": "2026-09-30T16:56:22", "sender": { "email": "piet@example.org", "alias": "Piet de Vries" }, "text": "Hoi Jan,\n\nAkkoord, zie de **getekende offerte** in de bijlage.\n\nGroet,\nPiet", "inlineImages": [], "attachments": [ { "id": "AAMkATT1…", "filename": "offerte-getekend.pdf", "contentType": "application/pdf", "contentId": null } ] }, { "date": "2026-09-29T10:15:00", "sender": { "email": "jan@example.com", "alias": "Jan Jansen" }, "text": "Beste Piet,\n\nHierbij de offerte. De planning staat in dit schema:\n\n\n\nMet vriendelijke groet,\nJan Jansen", "inlineImages": [ { "id": "AAMkATT2…", "filename": "image001.png", "contentType": "image/png", "contentId": "image001.png@01DD50FC.95EE0E50" } ], "attachments": [] } ] } ] } ``` Next to `status` and `error` the response holds `emails`. Every mail has: - `uniqueId` (string): The id of the mail. You use it for getting attachments, moving and setting the read status. - `conversationId` (string): The conversation the mail belongs to. - `path` (string[]): Where the mail is, in the same terms as the paths you read from and move to: `null` for the inbox, `["Facturen", "2026"]` for a folder in the inbox (with Google: the label `Facturen/2026`), and `[]` when no path points to where it is, such as the sent items or the archive. Useful when you read by `filterUniqueId` or `conversationId`: those find mails in every folder. - `received` (datetime): The moment of receipt, as the wall-clock time of the sender and without a time zone. A mail that came in at 14:56 UTC from a Dutch sender in summer has `16:56`. - `sender` (EmailAddress): The sender: `email` and `alias`. - `to, cc, bcc` (EmailAddress[]): The recipients. - `subject` (string): The subject. - `body` (string): The full content, as raw HTML. - `isRead` (bool): Whether the mail has been read. - `attachments` (Attachment[]): All attachments, including images that are part of the text. Per attachment: `id`, `filename`, `contentType` and `contentId`. You get the contents with Getting an attachment. - `messages` (Message[]): The mail split into separate messages. See Messages inside a mail. ### Sorting and paging - `1` NewToOld: Newest first. Use this one, unless you have a reason for the other. - `0` OldToNew: Oldest first. With Google the whole folder is read for this. Only use it with filters that keep the number of mails small, or on folders you keep empty by moving processed mails. With `skip` and `take` you page through a folder, 250 mails at a time: ```bash PAGE_SIZE=250 # the maximum per call SKIP=0 TOTAL=0 while :; do PAGE=$(curl -fsS -X POST "$BASE_URL/api/operation/readmails" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"emailAddress\": \"info@example.com\", \"path\": [\"Facturen\", \"2026\"], \"skip\": $SKIP, \"take\": $PAGE_SIZE, \"mailSort\": 1}") COUNT=$(jq '.emails | length' <<<"$PAGE") TOTAL=$(( TOTAL + COUNT )) (( COUNT < PAGE_SIZE )) && break # last page SKIP=$(( SKIP + PAGE_SIZE )) done echo "$TOTAL emails read" ``` > **Processing in a batch.** When new mail arrives while you are paging, the pages shift. For a batch this works better: read the first page, process every mail, move it to another folder and then read again from the start, until the folder is empty. ### Folders A path is a list of folder names, from top to bottom. Without a path you mean the inbox. - `["Verwerkt"]`: The folder Verwerkt in the inbox. - `["Facturen", "2026"]`: The folder 2026 inside the folder Facturen. - **Microsoft 365:** the path starts in the inbox and uses the names as the user sees them: `["Verwerkt"]` is the folder Verwerkt in the inbox, whatever the language of the mailbox. A path that starts with the inbox itself (`["Inbox", "Verwerkt"]`, or `["Postvak IN", "Verwerkt"]` in a Dutch mailbox) leads to the same folder. - **Google:** the path is a label. `["Facturen", "2026"]` is the label `Facturen/2026`. A mail with more labels: read from a label, its `path` is that label; read by id or conversation, it is `null` as long as the mail is also in the inbox, otherwise its deepest label. ## Messages inside a mail A mail is often a whole thread: a reply with the original message below it, or a forwarded mail. Mailbox Connector splits that thread into separate messages for you, each with a sender, a date and readable text. ### What you get Every mail from Reading mail has a list `messages`, with the newest message first. The first message is what the sender wrote; after that come the messages that were quoted below it. - `sender` (EmailAddress): Who wrote the message. For the first message that is the sender of the mail. For older messages it comes from the header above the message, and can be `null` when that header names no sender. - `date` (datetime): When the message was sent, as the wall-clock time of the sender. Can be `null` for older messages. - `text` (string): The text of this message only. - `inlineImages` (Attachment[]): The images that are part of the text of this message. You can send them back in a new mail; see Sending mail. - `attachments` (Attachment[]): The regular attachments of the mail. They are always with the first message. ### The text The HTML has been turned into text you can show or search right away: ```text Beste Piet, Hierbij de offerte. De planning staat in dit schema: Met vriendelijke groet, Jan Jansen ``` - `**text**`: Bold. - `_text_`: Italic. - `__text__`: Underlined. - ``: An image, at the place where it is in the message. After `cid:` comes the `id` of the attachment in `inlineImages`. Lines and paragraphs are as you see them in your mail program: an empty line where the mail program shows space between paragraphs, a single line break where the lines follow each other directly. ### Images with the right message An image in the text belongs to the message it is in, even when that message is three replies deep. So you can see in which message of the thread a diagram or screenshot was sent. You get the contents with Getting an attachment; that does not cost an action. Small pictures from signatures, such as social media icons, are left out. ### What is left out - Lines such as "Sent from my iPhone". - Lines with a disclaimer or a confidentiality notice. - The header above a quoted message (From, Sent, To, Subject) and the characters that mark a quotation. ### The limits > **Best effort, not guaranteed.** Every mail program writes a thread in its own way. The recognition works for the common forms in Dutch, English, German and French, and is extended where that turns out to be needed. Do not count on every thread being split perfectly. - Of a link the text remains, not the address behind it. - Lists and tables become plain lines. - When you need the formatting, use `body`: it holds the raw HTML of the whole mail. ## Getting an attachment Gets the contents of one attachment. Reading mail only returns the name and the type of an attachment; you get the contents here when you need them. `POST /api/operation/getattachment` (free) ### Request - `emailAddress` (string, required): The connected mailbox. - `emailId` (string, required): The `uniqueId` of the mail. - `attachmentId` (string, required): The `id` of the attachment, from `attachments` or `inlineImages`. ```bash # EMAIL_ID = the email's uniqueId and ATTACHMENT_ID = the attachment's id, both from ReadMails. # The response is a JSON string with base64: jq -r unwraps it, base64 decodes it. curl -fsS -X POST "$BASE_URL/api/operation/getattachment" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"emailAddress\": \"info@example.com\", \"emailId\": \"$EMAIL_ID\", \"attachmentId\": \"$ATTACHMENT_ID\"}" \ | jq -r '.' | base64 --decode > factuur.pdf ``` ### Response The response is not an object, but one JSON string with the contents as base64: ```json "JVBERi0xLjcKJeLjz9MKNSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDM4Pj5zdHJlYW0K…" ``` - When your application has no read permission on the mailbox, the response is empty. - When fetching at the mail provider fails, you get HTTP 500. > **Get first, move second.** A mail can get a new id when it is moved. So get attachments before you move the mail, or afterwards use the `uniqueId` from the response of Moving a mail. ## Checking a folder Checks whether a folder exists in a connected mailbox. Nothing is created. `POST /api/operation/checkpath` (1 action) ### Request - `emailAddress` (string, required): The connected mailbox. - `path` (string[], required): The folder, with at least one name. How a path works is explained with Reading mail under *Folders*. ```bash curl -fsS -X POST "$BASE_URL/api/operation/checkpath" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"emailAddress": "info@example.com", "path": ["Facturen", "2026"]}' ``` ### Response ```json { "status": 0, "error": null, "exists": true } ``` - `status` (int): `0` is success. See Statuses and errors. - `error` (string): The reason when it failed, otherwise `null`. - `exists` (bool): Whether the folder exists. ## Moving a mail Moves a mail to a folder. When the folder does not exist yet, it is created. You can mark the mail as read in the same call. `POST /api/operation/movemail` (1 action) ### Request - `emailAddress` (string, required): The connected mailbox. - `messageId` (string, required): The `uniqueId` of the mail. - `path` (string[], required): The folder the mail goes to, with at least one name. - `readStatus` (bool): `true` also marks the mail as read, `false` as unread. When you leave the field out, the read status does not change. ```bash # readStatus is optional: leave it out to keep the read status as it is. NEW_ID=$(curl -fsS -X POST "$BASE_URL/api/operation/movemail" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"emailAddress\": \"info@example.com\", \"messageId\": \"$EMAIL_ID\", \"path\": [\"Verwerkt\"], \"readStatus\": true}" \ | jq -r '.uniqueId') # A moved mail can get a new id. Use $NEW_ID from now on, not $EMAIL_ID. ``` ### Response ```json { "status": 0, "error": null, "uniqueId": "AAMkAGI2NGVhZTVlLTI1OGMtNDI4My1iZmE5LWJh…" } ``` - `status` (int): `0` is success. See Statuses and errors. - `error` (string): The reason when it failed, otherwise `null`. - `uniqueId` (string): The id of the mail after the move. > **Use the new id.** With Microsoft 365 a moved mail gets a new id; the old one no longer works after that. For everything you do with the mail after the move, use the `uniqueId` from this response. Google has no folders, but labels. Moving takes the mail out of the inbox and out of its other labels and gives it the label of the path. So afterwards the mail is in one place, just as with Microsoft 365. ## Setting the read status Marks a mail as read or unread, without moving it. When you want to move and mark a mail, do both at once with Moving a mail. `POST /api/operation/setreadstatus` (1 action) ### Request - `emailAddress` (string, required): The connected mailbox. - `emailId` (string, required): The `uniqueId` of the mail. - `readStatus` (bool, required): `true` is read, `false` is unread. ```bash # readStatus: true = read, false = unread curl -fsS -X POST "$BASE_URL/api/operation/setreadstatus" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"emailAddress\": \"info@example.com\", \"emailId\": \"$EMAIL_ID\", \"readStatus\": true}" ``` ### Response ```json { "status": 0, "error": null } ``` The response only holds `status` and `error`. ## Statuses and errors A call can fail at two levels: the HTTP status says whether your request arrived and was allowed, the field `status` in the response says whether the operation in the mailbox succeeded. Check both. ### HTTP status - `200` OK: The request has been processed. For operations, still look at `status`. - `401` Unauthorized: When logging in: the code or the security key is wrong. For other calls: the token is missing or has expired; log in again. - `403` Forbidden: When logging in: the application is locked for 5 minutes. For an operation: none of the mailboxes of your application has the permission for this operation. When a mailbox has just been connected, log in again. - `500` Server error: Something went wrong on our side. Try again later. ### The status field - `0` Success: The operation succeeded. - `1` Failure: The operation failed. `error` holds the reason. - `2` Unauthorized: This mailbox is not connected to your application, or not with the permission for this operation. See Connecting a mailbox. ```json { "status": 1, "error": "RateLimited" } ``` ### The error field With `status` 1, `error` holds one of these reasons, as text: - `InvalidRecipients`: One or more addresses were refused. Correct the addresses; trying again does not help. - `MessageTooLarge`: The mail is too large. Shrink or remove attachments. - `QuotaExceeded`: The mailbox has reached its sending limit or is full. Try again later. - `RateLimited`: Too many mails in a short time: a limit of Mailbox Connector or of the mail provider. Wait `retryAfterSeconds` seconds (or a minute when it is empty) and try again. See Limits and the spam check. - `TooManyRecipients`: More than 100 recipients in one mail. Split the mail; trying again does not help. - `SuspectedSpam`: The spam check refused the mail. Do not send it again unchanged: look at the content, the links and the attachments. Repeated refusals pause sending. - `SendingPaused`: Sending is paused for your application after repeated refusals by the spam check. Contact us; reading and moving mail keep working. - `ProviderUnavailable`: The mail provider is temporarily unavailable. Try again later. - `ReauthRequired`: The permission for the mailbox has been withdrawn or has expired. The mailbox has to be connected again. When it stays like this for 4 hours (and at least 10 calls), Mailbox Connector unlinks the mailbox and mails the administrators of your account. - `MailboxNotAvailable`: The mail provider has no working mailbox for this address (any more): for example the licence was removed, the user was deleted or the mailbox is not in the cloud. Trying again does not help; restore the mailbox at the provider or connect another one. When it stays like this for 4 hours (and at least 10 calls), Mailbox Connector unlinks the mailbox and mails the administrators of your account. - `UnexpectedError`: Another error, for example an unknown id or an empty path. ## Actions and costs Your usage is counted in actions. This page says what an action is, what is free and how the bundles work. ### What counts Every successful call of an operation is one action, however many mails are in the response. - `1` One action: Sending mail, creating a draft, reading mail, checking a folder, moving a mail and setting the read status. - `0` Free: Logging in, connecting a mailbox, getting attachments, and every call that did not succeed. ### An example - `1` Read: You read 250 mails in one call. - `0` Attachments: You get the attachments of all those mails. - `5` Move: You move five mails to another folder and mark them as read while doing so. - `6` Total: Six actions. ### Bundles - 50,000 actions per month are included. - When you use more, a bundle of 50,000 actions is added each time, for 5 euros. > **Mind how often you look.** A call that returns zero mails has succeeded as well, so it counts. Reading the inbox every minute uses more than 43,000 actions per month, even when nothing arrives. Looking every five minutes is enough for most uses and costs fewer than 9,000 actions.