# 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 @- <
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.
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