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.
Ready for AI assistants
Would you rather have an AI assistant write the integration? This documentation is also available in a form that assistants read well. See Building with AI.
How it works
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.
Connect a mailbox. The owner of the mailbox gives permission once, at Microsoft or Google. See Connecting a mailbox.
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:
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"
using System.Net.Http.Json;
var applicationId = "3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70";
var securityKey = "your-security-key"; // from a secret store, never from source control
var keyFile = "/etc/mailboxconnector/security.mckey";
using var http = new HttpClient { BaseAddress = new Uri("https://mailboxconnector.com") };
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
String baseUrl = "https://mailboxconnector.com";
String applicationId = "3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70";
String securityKey = "your-security-key"; // from a secret store, never from source control
Path keyFile = Path.of("/etc/mailboxconnector/security.mckey");
HttpClient http = HttpClient.newHttpClient();
ObjectMapper json = new ObjectMapper(); // Jackson
<?php
const BASE_URL = 'https://mailboxconnector.com';
const APPLICATION_ID = '3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70';
const SECURITY_KEY = 'your-security-key'; // from a secret store, never from source control
const KEY_FILE = '/etc/mailboxconnector/security.mckey';
import time
import requests
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"
const BASE_URL = 'https://mailboxconnector.com';
const APPLICATION_ID = '3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70';
const SECURITY_KEY = 'your-security-key'; // from a secret store, never from source control
const KEY_FILE = '/etc/mailboxconnector/security.mckey';
const (
baseURL = "https://mailboxconnector.com"
applicationID = "3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70"
securityKey = "your-security-key" // from a secret store, never from source control
keyFile = "/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.
Building with an AI assistant
Mailbox Connector is prepared for AI assistants such as Claude, ChatGPT and Copilot. You give your assistant one address; after that it knows how the API works and writes the integration in your programming language.
How it works
An AI assistant reads a page like this one poorly: it is made for people in a browser. That is why the same documentation is also available as plain text, and the calls in a description that programs can read. They are ordinary files; you can open them yourself.
The description of every call in OpenAPI format, for code generators and for assistants that work with it.
The text files are in English. Your assistant simply answers in your language.
How to use it
Pick your programming language below.
Copy the instruction and give it to your assistant. Change the last line to what you want to build.
Fill in your own settings in the result and test it.
Read https://mailboxconnector.com/llms-full.txt and write a Bash script (curl and jq) for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-csharp.txt and write a C# client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-java.txt and write a Java client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-php.txt and write a PHP client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-python.txt and write a Python client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-node.txt and write a Node.js client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Read https://mailboxconnector.com/llms-go.txt and write a Go client for the Mailbox Connector API.
Follow that documentation exactly:
- log in with the three steps (challenge, line from the key file, token) and reuse the token until a minute before it expires;
- read the key file without loading it into memory;
- on a 401 while logging in, wait a random moment and start again with a new challenge, three attempts at most;
- after every operation, check the status field of the response;
- read the application id, the security key and the path of the key file from configuration, never from the source code.
Then show me how to send a mail with an attachment and how to read the unread mails from the inbox.
Never give your keys to an assistant
Never paste your security key or the contents of your key file into a conversation with an AI assistant. The assistant does not need them to write the code: the code reads them from your configuration.
Check the result
An assistant usually writes good code, but not always. At the very least, check that the result does this:
The token is reused, and there is no new login for every call.
The key file is not loaded into memory as a whole.
On a 401 while logging in, a new challenge is fetched, with three attempts at most.
After every operation the field status is checked.
When in doubt, compare it with the complete client: that one has been tested.
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.
var challengeResponse = await http.GetFromJsonAsync<ChallengeResponse>($"/api/login/{applicationId}");
int challenge = challengeResponse!.Challenge;
record ChallengeResponse(int Challenge);
const challengeResponse = await fetch(`${BASE_URL}/api/login/${APPLICATION_ID}`);
if (!challengeResponse.ok) throw new Error(`Challenge request failed with HTTP ${challengeResponse.status}`);
const { challenge } = await challengeResponse.json();
response, err := http.Get(baseURL + "/api/login/" + applicationID)
if err != nil {
return err
}
defer response.Body.Close()
var challengeResponse struct {
Challenge int `json:"challenge"`
}
if err := json.NewDecoder(response.Body).Decode(&challengeResponse); err != nil {
return err
}
challenge := challengeResponse.Challenge
200Success
The response holds the challenge.
204No key file
No key file has been created for this application yet. Try again in a few minutes.
401Unknown
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.
security.mckey
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
# Skip $CHALLENGE lines and read the next one: challenge 0 is the first line of the file.
CODE=$(read_code "$KEY_FILE" "$CHALLENGE")
// Skip `challenge` lines and read the next one: challenge 0 is the first line of the file.
string code = KeyFile.ReadCode(keyFile, challenge);
// Skip `challenge` lines and read the next one: challenge 0 is the first line of the file.
String code = KeyFile.readCode(keyFile, challenge);
// Skip $challenge lines and read the next one: challenge 0 is the first line of the file.
$code = readCode(KEY_FILE, $challenge);
# Skip `challenge` lines and read the next one: challenge 0 is the first line of the file.
code = read_code(KEY_FILE, challenge)
// Skip `challenge` lines and read the next one: challenge 0 is the first line of the file.
const code = readCode(KEY_FILE, challenge);
// Skip `challenge` lines and read the next one: challenge 0 is the first line of the file.
code, err := readCode(keyFile, challenge)
if err != nil {
return err
}
The function that reads the line without loading the whole file is on Reading the key file.
Step 3: log in
POST/api/login
codestring required
The line from the key file that belongs to the challenge.
applicationIdstring required
The id of your application.
securityKeystring required
The security key of your application.
# 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 ))
using var loginResponse = await http.PostAsJsonAsync("/api/login", new
{
code,
applicationId,
securityKey
});
// 401 = wrong code (counts towards the lock), 403 = locked for 5 minutes
loginResponse.EnsureSuccessStatusCode();
var login = await loginResponse.Content.ReadFromJsonAsync<LoginResponse>();
string bearer = login!.Bearer;
DateTime validUntil = DateTime.UtcNow.AddMinutes(login.ValidMinutes);
record LoginResponse(int ValidMinutes, string Bearer);
The response holds the token. Earlier failures are cleared by this.
401Refused
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.
403Locked
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 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.
# 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'
}
using System.Buffers;
using System.Text;
public static class KeyFile
{
/// <summary>
/// Returns line <paramref name="challenge"/> (zero-based) of the key file.
/// The file is scanned in 64 KB blocks from a pooled buffer; only the
/// requested line is ever turned into a string.
/// </summary>
public static string ReadCode(string path, int challenge)
{
if (challenge < 0) throw new ArgumentOutOfRangeException(nameof(challenge));
using var file = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan);
byte[] buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
Span<byte> code = stackalloc byte[64]; // a line is at most 12 characters
int codeLength = 0;
int linesToSkip = challenge;
long position = 0;
int bytesRead;
while ((bytesRead = RandomAccess.Read(file, buffer, position)) > 0)
{
position += bytesRead;
ReadOnlySpan<byte> block = buffer.AsSpan(0, bytesRead);
// Skipping a line = finding the next '\n' (vectorised, no strings involved).
while (linesToSkip > 0)
{
int newline = block.IndexOf((byte)'\n');
if (newline < 0) break;
block = block[(newline + 1)..];
linesToSkip--;
}
if (linesToSkip > 0) continue;
// We are on the requested line; it may continue in the next block.
int end = block.IndexOf((byte)'\n');
ReadOnlySpan<byte> part = end < 0 ? block : block[..end];
part.CopyTo(code[codeLength..]);
codeLength += part.Length;
if (end >= 0) return ToCode(code[..codeLength]);
}
if (linesToSkip == 0 && codeLength > 0) return ToCode(code[..codeLength]); // last line without '\n'
throw new InvalidDataException($"Key file has no line {challenge}.");
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private static string ToCode(ReadOnlySpan<byte> line) => Encoding.ASCII.GetString(line.TrimEnd((byte)'\r'));
}
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
final class KeyFile {
private KeyFile() { }
/**
* Returns line {@code challenge} (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks that are read into one reusable buffer;
* skipping a line is just finding the next line feed, so only the requested
* line is ever turned into a String.
*/
static String readCode(Path path, int challenge) throws IOException {
if (challenge < 0) throw new IllegalArgumentException("challenge must not be negative");
ByteBuffer buffer = ByteBuffer.allocate(64 * 1024);
byte[] block = buffer.array();
byte[] code = new byte[64]; // a line is at most 12 characters
int codeLength = 0;
int linesToSkip = challenge;
try (FileChannel file = FileChannel.open(path, StandardOpenOption.READ)) {
int size;
while ((size = file.read(buffer.clear())) > 0) {
int position = 0;
while (linesToSkip > 0 && position < size) {
if (block[position++] == '\n') linesToSkip--;
}
if (linesToSkip > 0) continue; // requested line is not in this block
// We are on the requested line; it may continue in the next block.
while (position < size) {
byte b = block[position++];
if (b == '\n') return toCode(code, codeLength);
code[codeLength++] = b;
}
}
}
if (linesToSkip == 0 && codeLength > 0) return toCode(code, codeLength); // last line without line feed
throw new IOException("Key file has no line " + challenge);
}
private static String toCode(byte[] code, int length) {
if (length > 0 && code[length - 1] == '\r') length--;
return new String(code, 0, length, StandardCharsets.US_ASCII);
}
}
/**
* Returns line $challenge (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks; skipping lines is just counting "\n",
* so memory use stays at one block no matter which line is requested.
*/
function readCode(string $path, int $challenge): string
{
$handle = fopen($path, 'rb');
if ($handle === false || $challenge < 0) {
throw new RuntimeException("Cannot read line $challenge of key file $path");
}
try {
$linesToSkip = $challenge;
$code = '';
while (($block = fread($handle, 65536)) !== false && $block !== '') {
$position = 0;
if ($linesToSkip > 0) {
$newlines = substr_count($block, "\n");
if ($newlines < $linesToSkip) { // requested line is not in this block
$linesToSkip -= $newlines;
continue;
}
while ($linesToSkip > 0) {
$position = strpos($block, "\n", $position) + 1;
$linesToSkip--;
}
}
// We are on the requested line; it may continue in the next block.
$end = strpos($block, "\n", $position);
if ($end !== false) {
return rtrim($code . substr($block, $position, $end - $position), "\r");
}
$code .= substr($block, $position);
}
if ($linesToSkip === 0 && $code !== '') {
return rtrim($code, "\r"); // last line without "\n"
}
throw new RuntimeException("Key file has no line $challenge");
} finally {
fclose($handle);
}
}
def read_code(path: str, challenge: int) -> str:
"""Return line `challenge` (zero-based) of the key file.
The file is scanned in 64 KB blocks that are read into one reusable buffer;
skipping lines is just counting newlines, so no line is ever materialised
except the requested one.
"""
if challenge < 0:
raise ValueError("challenge must not be negative")
buffer = bytearray(64 * 1024)
lines_to_skip = challenge
code = bytearray()
with open(path, "rb", buffering=0) as file:
while (size := file.readinto(buffer)) > 0:
position = 0
if lines_to_skip > 0:
newlines = buffer.count(b"\n", 0, size)
if newlines < lines_to_skip: # requested line is not in this block
lines_to_skip -= newlines
continue
while lines_to_skip > 0:
position = buffer.index(b"\n", position, size) + 1
lines_to_skip -= 1
# We are on the requested line; it may continue in the next block.
end = buffer.find(b"\n", position, size)
if end >= 0:
code += buffer[position:end]
return code.decode("ascii").rstrip("\r")
code += buffer[position:size]
if lines_to_skip == 0 and code:
return code.decode("ascii").rstrip("\r") # last line without "\n"
raise ValueError(f"key file has no line {challenge}")
import { closeSync, openSync, readSync } from 'node:fs';
/**
* Returns line `challenge` (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks that are read into one reusable buffer;
* skipping a line is just finding the next "\n", so only the requested line
* is ever turned into a string.
*/
export function readCode(path, challenge) {
if (!Number.isInteger(challenge) || challenge < 0) throw new RangeError('challenge must be a non-negative integer');
const NEWLINE = 0x0a;
const buffer = Buffer.allocUnsafe(64 * 1024);
const file = openSync(path, 'r');
try {
let linesToSkip = challenge;
let code = '';
let size;
while ((size = readSync(file, buffer, 0, buffer.length, null)) > 0) {
const block = buffer.subarray(0, size);
let position = 0;
while (linesToSkip > 0) {
const newline = block.indexOf(NEWLINE, position);
if (newline === -1) break;
position = newline + 1;
linesToSkip--;
}
if (linesToSkip > 0) continue; // requested line is not in this block
// We are on the requested line; it may continue in the next block.
const end = block.indexOf(NEWLINE, position);
if (end !== -1) return (code + block.toString('latin1', position, end)).replace(/\r$/, '');
code += block.toString('latin1', position, size);
}
if (linesToSkip === 0 && code !== '') return code.replace(/\r$/, ''); // last line without "\n"
throw new Error(`Key file has no line ${challenge}`);
} finally {
closeSync(file);
}
}
import (
"bytes"
"errors"
"fmt"
"io"
"os"
)
// readCode returns line `challenge` (zero-based) of the key file.
//
// The file is scanned in 64 KB blocks that are read into one reusable buffer;
// skipping a line is just finding the next line feed, so only the requested
// line is ever turned into a string.
func readCode(path string, challenge int) (string, error) {
if challenge < 0 {
return "", errors.New("challenge must not be negative")
}
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
buffer := make([]byte, 64*1024)
code := make([]byte, 0, 64) // a line is at most 12 characters
linesToSkip := challenge
for {
size, err := file.Read(buffer)
block := buffer[:size]
for linesToSkip > 0 {
newline := bytes.IndexByte(block, '\n')
if newline < 0 {
break // requested line is not in this block
}
block = block[newline+1:]
linesToSkip--
}
if linesToSkip == 0 {
// We are on the requested line; it may continue in the next block.
if end := bytes.IndexByte(block, '\n'); end >= 0 {
code = append(code, block[:end]...)
return string(bytes.TrimSuffix(code, []byte("\r"))), nil
}
code = append(code, block...)
}
if err == io.EOF {
break
}
if err != nil {
return "", err
}
}
if linesToSkip == 0 && len(code) > 0 {
return string(bytes.TrimSuffix(code, []byte("\r"))), nil // last line without line feed
}
return "", fmt.Errorf("key file has no line %d", challenge)
}
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
401Wrong code
Counts as one failure for the application, whichever address it comes from.
401Wrong security key
Counts as one failure for the address it comes from. It does not lock the application.
403More 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.
200Successful 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
Reuse the token. It is valid for 10 minutes. Only log in again when it expires within a minute.
One login at a time per process. Let simultaneous calls wait for the same login instead of each logging in themselves.
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.
On a 403: stop. Wait 5 minutes. Trying again does not help.
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.
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.
#!/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
}
using System.Buffers;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
/// <summary>
/// Minimal Mailbox Connector client. Register it as a singleton: the JWT lives
/// in the instance, so every extra instance means an extra login.
/// </summary>
public sealed class MailboxConnectorClient : IDisposable
{
private const int MaxLoginAttempts = 3; // every 401 counts towards the lock, so keep this low
private static readonly TimeSpan RefreshMargin = TimeSpan.FromMinutes(1);
private readonly HttpClient _http;
private readonly string _securityKey;
private readonly string _keyFile;
private readonly SemaphoreSlim _loginLock = new(1, 1);
private volatile Token? _token;
public string ApplicationId { get; }
public MailboxConnectorClient(string baseUrl, string applicationId, string securityKey, string keyFile)
{
_http = new HttpClient { BaseAddress = new Uri(baseUrl), Timeout = TimeSpan.FromSeconds(30) };
ApplicationId = applicationId;
_securityKey = securityKey;
_keyFile = keyFile;
}
/// <summary>POSTs a JSON body to an operation and returns the deserialised response.</summary>
public async Task<T> PostAsync<T>(string path, object body, CancellationToken cancellationToken = default)
{
string bearer = await GetBearerAsync(cancellationToken);
using var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = JsonContent.Create(body) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
using var response = await _http.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<T>(cancellationToken))!;
}
private async Task<string> GetBearerAsync(CancellationToken cancellationToken)
{
if (_token is { IsFresh: true } cached) return cached.Bearer;
await _loginLock.WaitAsync(cancellationToken); // one login at a time within this process
try
{
if (_token is { IsFresh: true } justRefreshed) return justRefreshed.Bearer;
for (int attempt = 1; attempt <= MaxLoginAttempts; attempt++)
{
// Step 1: ask for a challenge.
var challenge = await _http.GetFromJsonAsync<ChallengeResponse>($"/api/login/{ApplicationId}", cancellationToken);
// Step 2: look up the matching line in the key file.
string code = KeyFile.ReadCode(_keyFile, challenge!.Challenge);
// Step 3: exchange the code for a JWT.
using var response = await _http.PostAsJsonAsync("/api/login",
new { code, applicationId = ApplicationId, securityKey = _securityKey }, cancellationToken);
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new MailboxConnectorLoginException("Locked after too many wrong codes. Wait 5 minutes before logging in again.");
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// 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.
await Task.Delay(Random.Shared.Next(200, 1000), cancellationToken);
continue;
}
response.EnsureSuccessStatusCode();
var login = await response.Content.ReadFromJsonAsync<LoginResponse>(cancellationToken);
_token = new Token(login!.Bearer, DateTime.UtcNow.AddMinutes(login.ValidMinutes));
return login.Bearer;
}
throw new MailboxConnectorLoginException($"Login failed after {MaxLoginAttempts} attempts.");
}
finally
{
_loginLock.Release();
}
}
public void Dispose()
{
_http.Dispose();
_loginLock.Dispose();
}
private sealed record ChallengeResponse(int Challenge);
private sealed record LoginResponse(int ValidMinutes, string Bearer);
private sealed record Token(string Bearer, DateTime ValidUntil)
{
public bool IsFresh => ValidUntil - RefreshMargin > DateTime.UtcNow;
}
}
public sealed class MailboxConnectorLoginException : Exception
{
public MailboxConnectorLoginException(string message) : base(message) { }
}
public enum ResponseStatus { Success = 0, Failure = 1, Unauthorized = 2 }
public static class KeyFile
{
/// <summary>
/// Returns line <paramref name="challenge"/> (zero-based) of the key file.
/// The file is scanned in 64 KB blocks from a pooled buffer; only the
/// requested line is ever turned into a string.
/// </summary>
public static string ReadCode(string path, int challenge)
{
if (challenge < 0) throw new ArgumentOutOfRangeException(nameof(challenge));
using var file = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan);
byte[] buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
Span<byte> code = stackalloc byte[64]; // a line is at most 12 characters
int codeLength = 0;
int linesToSkip = challenge;
long position = 0;
int bytesRead;
while ((bytesRead = RandomAccess.Read(file, buffer, position)) > 0)
{
position += bytesRead;
ReadOnlySpan<byte> block = buffer.AsSpan(0, bytesRead);
// Skipping a line = finding the next '\n' (vectorised, no strings involved).
while (linesToSkip > 0)
{
int newline = block.IndexOf((byte)'\n');
if (newline < 0) break;
block = block[(newline + 1)..];
linesToSkip--;
}
if (linesToSkip > 0) continue;
// We are on the requested line; it may continue in the next block.
int end = block.IndexOf((byte)'\n');
ReadOnlySpan<byte> part = end < 0 ? block : block[..end];
part.CopyTo(code[codeLength..]);
codeLength += part.Length;
if (end >= 0) return ToCode(code[..codeLength]);
}
if (linesToSkip == 0 && codeLength > 0) return ToCode(code[..codeLength]); // last line without '\n'
throw new InvalidDataException($"Key file has no line {challenge}.");
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private static string ToCode(ReadOnlySpan<byte> line) => Encoding.ASCII.GetString(line.TrimEnd((byte)'\r'));
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/**
* Minimal Mailbox Connector client (Java 17 or newer, Jackson for JSON).
*
* Create one instance per process and share it: the JWT lives in the
* instance, so every extra instance means an extra login.
*/
public final class MailboxConnectorClient {
private static final int MAX_LOGIN_ATTEMPTS = 3; // every 401 counts towards the lock, so keep this low
private static final Duration REFRESH_MARGIN = Duration.ofMinutes(1);
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
private final ObjectMapper json = new ObjectMapper();
private final String baseUrl;
private final String applicationId;
private final String securityKey;
private final Path keyFile;
private String bearer;
private Instant validUntil = Instant.MIN;
public MailboxConnectorClient(String baseUrl, String applicationId, String securityKey, Path keyFile) {
this.baseUrl = baseUrl;
this.applicationId = applicationId;
this.securityKey = securityKey;
this.keyFile = keyFile;
}
/** POSTs a JSON body to an operation and returns the decoded response. */
public JsonNode post(String path, Object body) throws IOException, InterruptedException {
HttpResponse<String> response = send(path, body, getBearer());
if (response.statusCode() != 200)
throw new IOException("Mailbox Connector returned HTTP " + response.statusCode() + " for " + path);
return json.readTree(response.body());
}
// synchronized: one login at a time within this process
private synchronized String getBearer() throws IOException, InterruptedException {
if (bearer != null && validUntil.minus(REFRESH_MARGIN).isAfter(Instant.now()))
return bearer;
for (int attempt = 1; attempt <= MAX_LOGIN_ATTEMPTS; attempt++) {
// Step 1: ask for a challenge.
HttpResponse<String> challengeResponse = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/api/login/" + applicationId)).GET().build(),
HttpResponse.BodyHandlers.ofString());
if (challengeResponse.statusCode() != 200)
throw new IOException("Challenge request failed with HTTP " + challengeResponse.statusCode());
int challenge = json.readTree(challengeResponse.body()).get("challenge").asInt();
// Step 2: look up the matching line in the key file.
String code = KeyFile.readCode(keyFile, challenge);
// Step 3: exchange the code for a JWT.
HttpResponse<String> response = send("/api/login",
Map.of("code", code, "applicationId", applicationId, "securityKey", securityKey), null);
if (response.statusCode() == 403)
throw new IOException("Locked after too many wrong codes. Wait 5 minutes before logging in again.");
if (response.statusCode() == 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.
Thread.sleep(ThreadLocalRandom.current().nextInt(200, 1000));
continue;
}
if (response.statusCode() != 200)
throw new IOException("Login failed with HTTP " + response.statusCode());
JsonNode login = json.readTree(response.body());
validUntil = Instant.now().plus(Duration.ofMinutes(login.get("validMinutes").asInt()));
bearer = login.get("bearer").asText();
return bearer;
}
throw new IOException("Login failed after " + MAX_LOGIN_ATTEMPTS + " attempts");
}
private HttpResponse<String> send(String path, Object body, String bearer) throws IOException, InterruptedException {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(baseUrl + path))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)));
if (bearer != null)
request.header("Authorization", "Bearer " + bearer);
return http.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
}
final class KeyFile {
private KeyFile() { }
/**
* Returns line {@code challenge} (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks that are read into one reusable buffer;
* skipping a line is just finding the next line feed, so only the requested
* line is ever turned into a String.
*/
static String readCode(Path path, int challenge) throws IOException {
if (challenge < 0) throw new IllegalArgumentException("challenge must not be negative");
ByteBuffer buffer = ByteBuffer.allocate(64 * 1024);
byte[] block = buffer.array();
byte[] code = new byte[64]; // a line is at most 12 characters
int codeLength = 0;
int linesToSkip = challenge;
try (FileChannel file = FileChannel.open(path, StandardOpenOption.READ)) {
int size;
while ((size = file.read(buffer.clear())) > 0) {
int position = 0;
while (linesToSkip > 0 && position < size) {
if (block[position++] == '\n') linesToSkip--;
}
if (linesToSkip > 0) continue; // requested line is not in this block
// We are on the requested line; it may continue in the next block.
while (position < size) {
byte b = block[position++];
if (b == '\n') return toCode(code, codeLength);
code[codeLength++] = b;
}
}
}
if (linesToSkip == 0 && codeLength > 0) return toCode(code, codeLength); // last line without line feed
throw new IOException("Key file has no line " + challenge);
}
private static String toCode(byte[] code, int length) {
if (length > 0 && code[length - 1] == '\r') length--;
return new String(code, 0, length, StandardCharsets.US_ASCII);
}
}
<?php
declare(strict_types=1);
/**
* Minimal Mailbox Connector client.
*
* PHP starts every request with empty memory, so the JWT is kept in a small
* file. The exclusive lock on that file also makes sure that only one PHP
* process on this server logs in at a time.
*/
final class MailboxConnectorClient
{
private const MAX_LOGIN_ATTEMPTS = 3; // every 401 counts towards the lock, so keep this low
private const REFRESH_MARGIN = 60; // seconds
private ?string $bearer = null;
private int $validUntil = 0;
public function __construct(
private readonly string $baseUrl,
public readonly string $applicationId,
private readonly string $securityKey,
private readonly string $keyFile,
private readonly ?string $tokenFile = null,
) {
}
/** POSTs a JSON body to an operation and returns the decoded response. */
public function post(string $path, array $body): mixed
{
[$status, $data] = $this->request('POST', $path, $body, $this->bearer());
if ($status !== 200) {
throw new RuntimeException("Mailbox Connector returned HTTP $status for $path");
}
return $data;
}
private function bearer(): string
{
if ($this->bearer !== null && $this->validUntil - self::REFRESH_MARGIN > time()) {
return $this->bearer;
}
$file = $this->tokenFile ?? sys_get_temp_dir() . "/mailboxconnector-{$this->applicationId}.token";
$handle = fopen($file, 'c+');
if ($handle === false) {
throw new RuntimeException("Cannot open token file $file");
}
@chmod($file, 0600);
flock($handle, LOCK_EX); // other PHP processes wait here
try {
$token = json_decode((string) stream_get_contents($handle), true);
if (!is_array($token) || $token['validUntil'] - self::REFRESH_MARGIN <= time()) {
$token = $this->login();
rewind($handle);
ftruncate($handle, 0);
fwrite($handle, json_encode($token));
}
$this->validUntil = $token['validUntil'];
return $this->bearer = $token['bearer'];
} finally {
flock($handle, LOCK_UN);
fclose($handle);
}
}
/** @return array{bearer: string, validUntil: int} */
private function login(): array
{
for ($attempt = 1; $attempt <= self::MAX_LOGIN_ATTEMPTS; $attempt++) {
// Step 1: ask for a challenge.
[$status, $challenge] = $this->request('GET', "/api/login/{$this->applicationId}");
if ($status !== 200) {
throw new RuntimeException("Challenge request failed with HTTP $status");
}
// Step 2: look up the matching line in the key file.
$code = readCode($this->keyFile, $challenge['challenge']);
// Step 3: exchange the code for a JWT.
[$status, $login] = $this->request('POST', '/api/login', [
'code' => $code,
'applicationId' => $this->applicationId,
'securityKey' => $this->securityKey,
]);
if ($status === 200) {
return ['bearer' => $login['bearer'], 'validUntil' => time() + $login['validMinutes'] * 60];
}
if ($status === 403) {
throw new RuntimeException('Locked after too many wrong codes. Wait 5 minutes before logging in again.');
}
if ($status !== 401) {
throw new RuntimeException("Login failed with HTTP $status");
}
// 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.
usleep(random_int(200_000, 1_000_000));
}
throw new RuntimeException('Login failed after ' . self::MAX_LOGIN_ATTEMPTS . ' attempts');
}
/** @return array{0: int, 1: mixed} HTTP status and decoded JSON body */
private function request(string $method, string $path, ?array $body = null, ?string $bearer = null): array
{
$headers = ['Accept: application/json'];
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
];
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
$options[CURLOPT_POSTFIELDS] = json_encode($body, JSON_THROW_ON_ERROR);
}
if ($bearer !== null) {
$headers[] = "Authorization: Bearer $bearer";
}
$options[CURLOPT_HTTPHEADER] = $headers;
$ch = curl_init($this->baseUrl . $path);
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException('Mailbox Connector is unreachable: ' . curl_error($ch));
}
return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), $raw === '' ? null : json_decode($raw, true)];
}
}
/**
* Returns line $challenge (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks; skipping lines is just counting "\n",
* so memory use stays at one block no matter which line is requested.
*/
function readCode(string $path, int $challenge): string
{
$handle = fopen($path, 'rb');
if ($handle === false || $challenge < 0) {
throw new RuntimeException("Cannot read line $challenge of key file $path");
}
try {
$linesToSkip = $challenge;
$code = '';
while (($block = fread($handle, 65536)) !== false && $block !== '') {
$position = 0;
if ($linesToSkip > 0) {
$newlines = substr_count($block, "\n");
if ($newlines < $linesToSkip) { // requested line is not in this block
$linesToSkip -= $newlines;
continue;
}
while ($linesToSkip > 0) {
$position = strpos($block, "\n", $position) + 1;
$linesToSkip--;
}
}
// We are on the requested line; it may continue in the next block.
$end = strpos($block, "\n", $position);
if ($end !== false) {
return rtrim($code . substr($block, $position, $end - $position), "\r");
}
$code .= substr($block, $position);
}
if ($linesToSkip === 0 && $code !== '') {
return rtrim($code, "\r"); // last line without "\n"
}
throw new RuntimeException("Key file has no line $challenge");
} finally {
fclose($handle);
}
}
import random
import threading
import time
import requests
class MailboxConnectorLoginError(Exception):
pass
class MailboxConnectorClient:
"""Minimal Mailbox Connector client.
Create one instance per process and share it: the JWT lives in the
instance, so every extra instance means an extra login.
"""
MAX_LOGIN_ATTEMPTS = 3 # every 401 counts towards the lock, so keep this low
REFRESH_MARGIN = 60 # seconds
def __init__(self, base_url: str, application_id: str, security_key: str, key_file: str):
self.base_url = base_url.rstrip("/")
self.application_id = application_id
self._security_key = security_key
self._key_file = key_file
self._session = requests.Session()
self._login_lock = threading.Lock()
self._bearer = None
self._valid_until = 0.0
def post(self, path: str, body: dict):
"""POST a JSON body to an operation and return the decoded response."""
response = self._session.post(
self.base_url + path,
json=body,
headers={"Authorization": f"Bearer {self._get_bearer()}"},
timeout=30,
)
response.raise_for_status()
return response.json()
def _token_is_fresh(self) -> bool:
return self._bearer is not None and self._valid_until - self.REFRESH_MARGIN > time.time()
def _get_bearer(self) -> str:
if self._token_is_fresh():
return self._bearer
with self._login_lock: # one login at a time within this process
if self._token_is_fresh(): # another thread logged in while we waited
return self._bearer
for _ in range(self.MAX_LOGIN_ATTEMPTS):
# Step 1: ask for a challenge.
response = self._session.get(f"{self.base_url}/api/login/{self.application_id}", timeout=30)
response.raise_for_status()
# Step 2: look up the matching line in the key file.
code = read_code(self._key_file, response.json()["challenge"])
# Step 3: exchange the code for a JWT.
response = self._session.post(f"{self.base_url}/api/login", timeout=30, json={
"code": code,
"applicationId": self.application_id,
"securityKey": self._security_key,
})
if response.status_code == 403:
raise MailboxConnectorLoginError(
"Locked after too many wrong codes. Wait 5 minutes before logging in again.")
if response.status_code == 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.
time.sleep(random.uniform(0.2, 1.0))
continue
response.raise_for_status()
login = response.json()
self._valid_until = time.time() + login["validMinutes"] * 60
self._bearer = login["bearer"]
return self._bearer
raise MailboxConnectorLoginError(f"Login failed after {self.MAX_LOGIN_ATTEMPTS} attempts")
def read_code(path: str, challenge: int) -> str:
"""Return line `challenge` (zero-based) of the key file.
The file is scanned in 64 KB blocks that are read into one reusable buffer;
skipping lines is just counting newlines, so no line is ever materialised
except the requested one.
"""
if challenge < 0:
raise ValueError("challenge must not be negative")
buffer = bytearray(64 * 1024)
lines_to_skip = challenge
code = bytearray()
with open(path, "rb", buffering=0) as file:
while (size := file.readinto(buffer)) > 0:
position = 0
if lines_to_skip > 0:
newlines = buffer.count(b"\n", 0, size)
if newlines < lines_to_skip: # requested line is not in this block
lines_to_skip -= newlines
continue
while lines_to_skip > 0:
position = buffer.index(b"\n", position, size) + 1
lines_to_skip -= 1
# We are on the requested line; it may continue in the next block.
end = buffer.find(b"\n", position, size)
if end >= 0:
code += buffer[position:end]
return code.decode("ascii").rstrip("\r")
code += buffer[position:size]
if lines_to_skip == 0 and code:
return code.decode("ascii").rstrip("\r") # last line without "\n"
raise ValueError(f"key file has no line {challenge}")
import { closeSync, openSync, readSync } from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
/**
* Minimal Mailbox Connector client (Node.js 18 or newer).
*
* Create one instance per process and share it: the JWT lives in the
* instance, so every extra instance means an extra login.
*/
export class MailboxConnectorClient {
static MAX_LOGIN_ATTEMPTS = 3; // every 401 counts towards the lock, so keep this low
static REFRESH_MARGIN = 60_000; // milliseconds
#securityKey;
#keyFile;
#bearer = null;
#validUntil = 0;
#loginInProgress = null;
constructor({ baseUrl, applicationId, securityKey, keyFile }) {
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.applicationId = applicationId;
this.#securityKey = securityKey;
this.#keyFile = keyFile;
}
/** POSTs a JSON body to an operation and returns the decoded response. */
async post(path, body) {
const response = await fetch(this.baseUrl + path, {
method: 'POST',
headers: {
Authorization: `Bearer ${await this.#getBearer()}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`Mailbox Connector returned HTTP ${response.status} for ${path}`);
return response.json();
}
#getBearer() {
if (this.#bearer && this.#validUntil - MailboxConnectorClient.REFRESH_MARGIN > Date.now()) {
return this.#bearer;
}
// One login at a time within this process: concurrent callers share the same promise.
this.#loginInProgress ??= this.#login().finally(() => { this.#loginInProgress = null; });
return this.#loginInProgress;
}
async #login() {
for (let attempt = 1; attempt <= MailboxConnectorClient.MAX_LOGIN_ATTEMPTS; attempt++) {
// Step 1: ask for a challenge.
const challengeResponse = await fetch(`${this.baseUrl}/api/login/${this.applicationId}`);
if (!challengeResponse.ok) throw new Error(`Challenge request failed with HTTP ${challengeResponse.status}`);
const { challenge } = await challengeResponse.json();
// Step 2: look up the matching line in the key file.
const code = readCode(this.#keyFile, challenge);
// Step 3: exchange the code for a JWT.
const loginResponse = await fetch(`${this.baseUrl}/api/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, applicationId: this.applicationId, securityKey: this.#securityKey }),
});
if (loginResponse.status === 403) {
throw new Error('Locked after too many wrong codes. Wait 5 minutes before logging in again.');
}
if (loginResponse.status === 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.
await sleep(200 + Math.random() * 800);
continue;
}
if (!loginResponse.ok) throw new Error(`Login failed with HTTP ${loginResponse.status}`);
const { bearer, validMinutes } = await loginResponse.json();
this.#validUntil = Date.now() + validMinutes * 60_000;
this.#bearer = bearer;
return bearer;
}
throw new Error(`Login failed after ${MailboxConnectorClient.MAX_LOGIN_ATTEMPTS} attempts`);
}
}
/**
* Returns line `challenge` (zero-based) of the key file.
*
* The file is scanned in 64 KB blocks that are read into one reusable buffer;
* skipping a line is just finding the next "\n", so only the requested line
* is ever turned into a string.
*/
export function readCode(path, challenge) {
if (!Number.isInteger(challenge) || challenge < 0) throw new RangeError('challenge must be a non-negative integer');
const NEWLINE = 0x0a;
const buffer = Buffer.allocUnsafe(64 * 1024);
const file = openSync(path, 'r');
try {
let linesToSkip = challenge;
let code = '';
let size;
while ((size = readSync(file, buffer, 0, buffer.length, null)) > 0) {
const block = buffer.subarray(0, size);
let position = 0;
while (linesToSkip > 0) {
const newline = block.indexOf(NEWLINE, position);
if (newline === -1) break;
position = newline + 1;
linesToSkip--;
}
if (linesToSkip > 0) continue; // requested line is not in this block
// We are on the requested line; it may continue in the next block.
const end = block.indexOf(NEWLINE, position);
if (end !== -1) return (code + block.toString('latin1', position, end)).replace(/\r$/, '');
code += block.toString('latin1', position, size);
}
if (linesToSkip === 0 && code !== '') return code.replace(/\r$/, ''); // last line without "\n"
throw new Error(`Key file has no line ${challenge}`);
} finally {
closeSync(file);
}
}
package mailboxconnector
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"sync"
"time"
)
const (
maxLoginAttempts = 3 // every 401 counts towards the lock, so keep this low
refreshMargin = time.Minute
)
var httpClient = &http.Client{Timeout: 30 * time.Second}
// Client is a minimal Mailbox Connector client.
//
// Create one Client per process and share it: the JWT lives in the Client, so
// every extra Client means an extra login. A Client is safe for concurrent use.
type Client struct {
BaseURL string
ApplicationID string
SecurityKey string
KeyFile string
mu sync.Mutex // one login at a time within this process
bearer string
validUntil time.Time
}
// Post sends a JSON body to an operation and decodes the response into result.
func (c *Client) Post(path string, body, result any) error {
bearer, err := c.getBearer()
if err != nil {
return err
}
response, err := c.send(path, body, bearer)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("mailbox connector returned HTTP %d for %s", response.StatusCode, path)
}
return json.NewDecoder(response.Body).Decode(result)
}
func (c *Client) getBearer() (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.bearer != "" && time.Until(c.validUntil) > refreshMargin {
return c.bearer, nil
}
for attempt := 1; attempt <= maxLoginAttempts; attempt++ {
// Step 1: ask for a challenge.
challenge, err := c.challenge()
if err != nil {
return "", err
}
// Step 2: look up the matching line in the key file.
code, err := readCode(c.KeyFile, challenge)
if err != nil {
return "", err
}
// Step 3: exchange the code for a JWT.
response, err := c.send("/api/login", map[string]string{
"code": code,
"applicationId": c.ApplicationID,
"securityKey": c.SecurityKey,
}, "")
if err != nil {
return "", err
}
var login struct {
Bearer string `json:"bearer"`
ValidMinutes int `json:"validMinutes"`
}
if response.StatusCode == http.StatusOK {
err = json.NewDecoder(response.Body).Decode(&login)
}
response.Body.Close()
switch {
case err != nil:
return "", err
case response.StatusCode == http.StatusOK:
c.bearer = login.Bearer
c.validUntil = time.Now().Add(time.Duration(login.ValidMinutes) * time.Minute)
return c.bearer, nil
case response.StatusCode == http.StatusForbidden:
return "", errors.New("locked after too many wrong codes; wait 5 minutes before logging in again")
case response.StatusCode != http.StatusUnauthorized:
return "", fmt.Errorf("login failed with HTTP %d", response.StatusCode)
}
// 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.
time.Sleep(time.Duration(200+rand.Intn(800)) * time.Millisecond)
}
return "", fmt.Errorf("login failed after %d attempts", maxLoginAttempts)
}
func (c *Client) challenge() (int, error) {
response, err := httpClient.Get(c.BaseURL + "/api/login/" + c.ApplicationID)
if err != nil {
return 0, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return 0, fmt.Errorf("challenge request failed with HTTP %d", response.StatusCode)
}
var result struct {
Challenge int `json:"challenge"`
}
err = json.NewDecoder(response.Body).Decode(&result)
return result.Challenge, err
}
func (c *Client) send(path string, body any, bearer string) (*http.Response, error) {
payload, err := json.Marshal(body)
if err != nil {
return nil, err
}
request, err := http.NewRequest(http.MethodPost, c.BaseURL+path, bytes.NewReader(payload))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
if bearer != "" {
request.Header.Set("Authorization", "Bearer "+bearer)
}
return httpClient.Do(request)
}
// readCode returns line `challenge` (zero-based) of the key file.
//
// The file is scanned in 64 KB blocks that are read into one reusable buffer;
// skipping a line is just finding the next line feed, so only the requested
// line is ever turned into a string.
func readCode(path string, challenge int) (string, error) {
if challenge < 0 {
return "", errors.New("challenge must not be negative")
}
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
buffer := make([]byte, 64*1024)
code := make([]byte, 0, 64) // a line is at most 12 characters
linesToSkip := challenge
for {
size, err := file.Read(buffer)
block := buffer[:size]
for linesToSkip > 0 {
newline := bytes.IndexByte(block, '\n')
if newline < 0 {
break // requested line is not in this block
}
block = block[newline+1:]
linesToSkip--
}
if linesToSkip == 0 {
// We are on the requested line; it may continue in the next block.
if end := bytes.IndexByte(block, '\n'); end >= 0 {
code = append(code, block[:end]...)
return string(bytes.TrimSuffix(code, []byte("\r"))), nil
}
code = append(code, block...)
}
if err == io.EOF {
break
}
if err != nil {
return "", err
}
}
if linesToSkip == 0 && len(code) > 0 {
return string(bytes.TrimSuffix(code, []byte("\r"))), nil // last line without line feed
}
return "", fmt.Errorf("key file has no line %d", challenge)
}
Another language, or do you want a client made to measure? An AI assistant writes it for you; see Building with AI.
Usage
The samples with the operations assume this client:
# Call mc_login before a request: it only logs in when the token is missing or about to expire.
mc_login
// One instance for the whole process, e.g. services.AddSingleton(client) in ASP.NET Core.
var client = new MailboxConnectorClient(
baseUrl: "https://mailboxconnector.com",
applicationId: "3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70",
securityKey: "your-security-key",
keyFile: "/etc/mailboxconnector/security.mckey");
// One instance for the whole process.
MailboxConnectorClient client = new MailboxConnectorClient(
"https://mailboxconnector.com",
"3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70",
"your-security-key",
Path.of("/etc/mailboxconnector/security.mckey"));
# One instance for the whole process.
client = MailboxConnectorClient(
base_url="https://mailboxconnector.com",
application_id="3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70",
security_key="your-security-key",
key_file="/etc/mailboxconnector/security.mckey",
)
// One instance for the whole process.
const client = new MailboxConnectorClient({
baseUrl: 'https://mailboxconnector.com',
applicationId: '3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70',
securityKey: 'your-security-key',
keyFile: '/etc/mailboxconnector/security.mckey',
});
// One Client for the whole process.
client := &Client{
BaseURL: "https://mailboxconnector.com",
ApplicationID: "3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70",
SecurityKey: "your-security-key",
KeyFile: "/etc/mailboxconnector/security.mckey",
}
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
Check whether the mailbox is connected already.
If not: create a connection request. You get an id back.
Send the user to https://mailboxconnector.com/connect/{id}.
There the user signs in at Microsoft or Google, as the mailbox itself, and gives permission.
After that the user returns to your returnUrl. Then check again whether the mailbox is connected.
Checking the connection
POST/api/connectionrequest/checkfree
desiredEmailAddressstring required
The address of the mailbox.
needsSendMailbool
You want to send mail.
needsCreateDraftbool
You want to create drafts.
needsReadMailbool
You want to read mail, get attachments and check folders.
var check = await client.PostAsync<CheckConnectionResponse>("/api/connectionrequest/check", new
{
logoUrl = "https://www.example.com/logo.png",
desiredEmailAddress = "info@example.com",
needsSendMail = true,
needsCreateDraft = false,
needsReadMail = true,
needsMoveMail = true
});
switch (check.ConnectionStatus)
{
case ConnectionStatus.Connected:
Console.WriteLine("Mailbox is connected with all requested permissions.");
break;
case ConnectionStatus.MissingPermissions:
Console.WriteLine("Mailbox is connected, but not for everything you asked. Create a new connection request.");
break;
case ConnectionStatus.NotConfigured:
Console.WriteLine("Mailbox is not connected yet. Create a connection request.");
break;
}
record CheckConnectionResponse(ConnectionStatus ConnectionStatus);
enum ConnectionStatus { NotConfigured = 0, MissingPermissions = 1, Connected = 2 }
JsonNode check = client.post("/api/connectionrequest/check", Map.of(
"logoUrl", "https://www.example.com/logo.png",
"desiredEmailAddress", "info@example.com",
"needsSendMail", true,
"needsCreateDraft", false,
"needsReadMail", true,
"needsMoveMail", true));
switch (check.get("connectionStatus").asInt()) {
case 2 -> System.out.println("Mailbox is connected with all requested permissions.");
case 1 -> System.out.println("Mailbox is connected, but not for everything you asked. Create a new connection request.");
default -> System.out.println("Mailbox is not connected yet. Create a connection request.");
}
$check = $client->post('/api/connectionrequest/check', [
'logoUrl' => 'https://www.example.com/logo.png',
'desiredEmailAddress' => 'info@example.com',
'needsSendMail' => true,
'needsCreateDraft' => false,
'needsReadMail' => true,
'needsMoveMail' => true,
]);
echo match ($check['connectionStatus']) {
2 => 'Mailbox is connected with all requested permissions.',
1 => 'Mailbox is connected, but not for everything you asked. Create a new connection request.',
0 => 'Mailbox is not connected yet. Create a connection request.',
}, PHP_EOL;
check = client.post("/api/connectionrequest/check", {
"logoUrl": "https://www.example.com/logo.png",
"desiredEmailAddress": "info@example.com",
"needsSendMail": True,
"needsCreateDraft": False,
"needsReadMail": True,
"needsMoveMail": True,
})
status = check["connectionStatus"]
if status == 2:
print("Mailbox is connected with all requested permissions.")
elif status == 1:
print("Mailbox is connected, but not for everything you asked. Create a new connection request.")
else:
print("Mailbox is not connected yet. Create a connection request.")
const check = await client.post('/api/connectionrequest/check', {
logoUrl: 'https://www.example.com/logo.png',
desiredEmailAddress: 'info@example.com',
needsSendMail: true,
needsCreateDraft: false,
needsReadMail: true,
needsMoveMail: true,
});
switch (check.connectionStatus) {
case 2:
console.log('Mailbox is connected with all requested permissions.');
break;
case 1:
console.log('Mailbox is connected, but not for everything you asked. Create a new connection request.');
break;
default:
console.log('Mailbox is not connected yet. Create a connection request.');
}
var check struct {
ConnectionStatus int `json:"connectionStatus"`
}
err := client.Post("/api/connectionrequest/check", map[string]any{
"logoUrl": "https://www.example.com/logo.png",
"desiredEmailAddress": "info@example.com",
"needsSendMail": true,
"needsCreateDraft": false,
"needsReadMail": true,
"needsMoveMail": true,
}, &check)
if err != nil {
return err
}
switch check.ConnectionStatus {
case 2:
fmt.Println("Mailbox is connected with all requested permissions.")
case 1:
fmt.Println("Mailbox is connected, but not for everything you asked. Create a new connection request.")
default:
fmt.Println("Mailbox is not connected yet. Create a connection request.")
}
Response
json
{
"connectionStatus": 2
}
The values of connectionStatus:
0NotConfigured
The mailbox is not connected to your application. Create a connection request.
1MissingPermissions
The mailbox is connected, but not for everything you ask. Create a new connection request with the permissions you need.
2Connected
The mailbox is connected with all requested permissions.
Creating a connection request
POST/api/connectionrequest/createfree
The same fields as for checking, plus:
returnUrlstring required
The page in your application the user returns to after connecting.
logoUrlstring
The logo of your application, for the connect page.
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"
var connection = await client.PostAsync<CreateConnectionResponse>("/api/connectionrequest/create", new
{
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
});
if (connection.Status != ResponseStatus.Success)
throw new InvalidOperationException($"CreateConnection failed: {connection.Error}");
// Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
Console.WriteLine($"https://mailboxconnector.com/connect/{connection.Id}");
record CreateConnectionResponse(ResponseStatus Status, string? Error, Guid Id);
JsonNode connection = client.post("/api/connectionrequest/create", Map.of(
"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));
if (connection.get("status").asInt() != 0)
throw new IllegalStateException("CreateConnection failed: " + connection.get("error").asText());
// Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
System.out.println("https://mailboxconnector.com/connect/" + connection.get("id").asText());
$connection = $client->post('/api/connectionrequest/create', [
'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,
]);
if ($connection['status'] !== 0) {
throw new RuntimeException('CreateConnection failed: ' . $connection['error']);
}
// Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
echo 'https://mailboxconnector.com/connect/', $connection['id'], PHP_EOL;
connection = client.post("/api/connectionrequest/create", {
"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,
})
if connection["status"] != 0:
raise RuntimeError(f"CreateConnection failed: {connection['error']}")
# Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
print(f"https://mailboxconnector.com/connect/{connection['id']}")
const connection = await client.post('/api/connectionrequest/create', {
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,
});
if (connection.status !== 0) throw new Error(`CreateConnection failed: ${connection.error}`);
// Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
console.log(`https://mailboxconnector.com/connect/${connection.id}`);
var connection struct {
Status int `json:"status"`
Error string `json:"error"`
ID string `json:"id"`
}
err := client.Post("/api/connectionrequest/create", map[string]any{
"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,
}, &connection)
if err != nil {
return err
}
if connection.Status != 0 {
return fmt.Errorf("CreateConnection failed: %s", connection.Error)
}
// Send the user to this page to connect the mailbox; afterwards they return to your returnUrl.
fmt.Println("https://mailboxconnector.com/connect/" + connection.ID)
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/sendmail1 action
Request
senderEmailAddress required
The connected mailbox you send from.
toEmailAddress[] required
The recipients.
ccEmailAddress[]
Recipients in copy.
bccEmailAddress[]
Recipients in blind copy.
subjectstring
The subject.
bodystring
The content, as HTML.
attachmentsMailAttachment[]
The attachments.
saveToSentItemsboolean
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
emailstring required
The e-mail address.
aliasstring
The name the recipient sees. When you leave it out, the part before the at sign is used.
MailAttachment
filenamestring required
The file name.
contentTypestring required
The type, for example application/pdf.
datastring required
The contents of the file, as base64.
contentIdstring
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.
var sent = await client.PostAsync<SendMailResponse>("/api/operation/sendmail", new
{
sender = new { email = "info@example.com", alias = "Example BV" },
to = new[] { new { email = "jan@example.org", alias = "Jan Jansen" } },
cc = new[] { new { email = "administratie@example.com", alias = "Administratie" } },
bcc = Array.Empty<object>(),
subject = "Factuur 2026-0042",
body = "<p>Beste Jan,</p><p>In de bijlage vind je de factuur.</p>",
attachments = new[]
{
new
{
filename = "factuur-2026-0042.pdf",
contentType = "application/pdf",
data = await File.ReadAllBytesAsync("factuur-2026-0042.pdf") // byte[] is serialised as base64
}
}
});
if (sent.Status != ResponseStatus.Success)
throw new InvalidOperationException($"SendMail failed: {sent.Error}");
Console.WriteLine("Sent");
record SendMailResponse(ResponseStatus Status, string? Error, string? MessageId);
JsonNode sent = client.post("/api/operation/sendmail", Map.of(
"sender", Map.of("email", "info@example.com", "alias", "Example BV"),
"to", List.of(Map.of("email", "jan@example.org", "alias", "Jan Jansen")),
"cc", List.of(Map.of("email", "administratie@example.com", "alias", "Administratie")),
"bcc", List.of(),
"subject", "Factuur 2026-0042",
"body", "<p>Beste Jan,</p><p>In de bijlage vind je de factuur.</p>",
"attachments", List.of(Map.of(
"filename", "factuur-2026-0042.pdf",
"contentType", "application/pdf",
"data", Files.readAllBytes(Path.of("factuur-2026-0042.pdf")))))); // byte[] is serialised as base64
if (sent.get("status").asInt() != 0)
throw new IllegalStateException("SendMail failed: " + sent.get("error").asText());
System.out.println("Sent");
import base64
with open("factuur-2026-0042.pdf", "rb") as pdf:
attachment_data = base64.b64encode(pdf.read()).decode("ascii")
sent = client.post("/api/operation/sendmail", {
"sender": {"email": "info@example.com", "alias": "Example BV"},
"to": [{"email": "jan@example.org", "alias": "Jan Jansen"}],
"cc": [{"email": "administratie@example.com", "alias": "Administratie"}],
"bcc": [],
"subject": "Factuur 2026-0042",
"body": "<p>Beste Jan,</p><p>In de bijlage vind je de factuur.</p>",
"attachments": [{
"filename": "factuur-2026-0042.pdf",
"contentType": "application/pdf",
"data": attachment_data,
}],
})
if sent["status"] != 0:
raise RuntimeError(f"SendMail failed: {sent['error']}")
print("Sent")
import { readFile } from 'node:fs/promises';
const sent = await client.post('/api/operation/sendmail', {
sender: { email: 'info@example.com', alias: 'Example BV' },
to: [{ email: 'jan@example.org', alias: 'Jan Jansen' }],
cc: [{ email: 'administratie@example.com', alias: 'Administratie' }],
bcc: [],
subject: 'Factuur 2026-0042',
body: '<p>Beste Jan,</p><p>In de bijlage vind je de factuur.</p>',
attachments: [{
filename: 'factuur-2026-0042.pdf',
contentType: 'application/pdf',
data: (await readFile('factuur-2026-0042.pdf')).toString('base64'),
}],
});
if (sent.status !== 0) throw new Error(`SendMail failed: ${sent.error}`);
console.log('Sent');
pdf, err := os.ReadFile("factuur-2026-0042.pdf")
if err != nil {
return err
}
var sent struct {
Status int `json:"status"`
Error string `json:"error"`
}
err = client.Post("/api/operation/sendmail", map[string]any{
"sender": map[string]string{"email": "info@example.com", "alias": "Example BV"},
"to": []map[string]string{{"email": "jan@example.org", "alias": "Jan Jansen"}},
"cc": []map[string]string{{"email": "administratie@example.com", "alias": "Administratie"}},
"bcc": []map[string]string{},
"subject": "Factuur 2026-0042",
"body": "<p>Beste Jan,</p><p>In de bijlage vind je de factuur.</p>",
"attachments": []map[string]any{{
"filename": "factuur-2026-0042.pdf",
"contentType": "application/pdf",
"data": pdf, // []byte is serialised as base64
}},
}, &sent)
if err != nil {
return err
}
if sent.Status != 0 {
return fmt.Errorf("SendMail failed: %s", sent.Error)
}
fmt.Println("Sent")
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.
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 <img src='cid:ID'>; those images are in inlineImages. Get the contents with Getting an attachment, send the image along with a contentId of your own, and put <img src="cid:..."> with that id at that place in your new text.
Not filled when sending. With Creating a draft this holds the id of the draft.
retryAfterSecondsint
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.
Per mailbox
Over all applications that send with that mailbox together.
20
Per minute.
300
Per hour.
1.500
Per 24 hours.
Per application
5.000
Mails per 24 hours, over all its mailboxes together.
100
Recipients per mail (to, cc and bcc together). More gives TooManyRecipients.
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
Every mail gets 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.
Next to status and error the response holds emails. Every mail has:
uniqueIdstring
The id of the mail. You use it for getting attachments, moving and setting the read status.
conversationIdstring
The conversation the mail belongs to.
pathstring[]
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. See Folders.
receiveddatetime
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.
senderEmailAddress
The sender: email and alias.
to, cc, bccEmailAddress[]
The recipients.
subjectstring
The subject.
bodystring
The full content, as raw HTML.
isReadbool
Whether the mail has been read.
attachmentsAttachment[]
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.
Newest first. Use this one, unless you have a reason for the other.
0OldToNew
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:
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"
const int PageSize = 250; // the maximum per call
var all = new List<Email>();
for (int skip = 0; ; skip += PageSize)
{
var page = await client.PostAsync<ReadMailsResponse>("/api/operation/readmails", new
{
emailAddress = "info@example.com",
path = new[] { "Facturen", "2026" },
skip,
take = PageSize,
mailSort = MailSort.NewToOld
});
if (page.Status != ResponseStatus.Success)
throw new InvalidOperationException($"ReadMails failed: {page.Error}");
all.AddRange(page.Emails);
if (page.Emails.Length < PageSize) break; // last page
}
Console.WriteLine($"{all.Count} emails read");
final int pageSize = 250; // the maximum per call
List<JsonNode> all = new ArrayList<>();
for (int skip = 0; ; skip += pageSize) {
JsonNode page = client.post("/api/operation/readmails", Map.of(
"emailAddress", "info@example.com",
"path", List.of("Facturen", "2026"),
"skip", skip,
"take", pageSize,
"mailSort", 1)); // NewToOld
if (page.get("status").asInt() != 0)
throw new IllegalStateException("ReadMails failed: " + page.get("error").asText());
page.get("emails").forEach(all::add);
if (page.get("emails").size() < pageSize) break; // last page
}
System.out.println(all.size() + " emails read");
const PAGE_SIZE = 250; // the maximum per call
$all = [];
for ($skip = 0; ; $skip += PAGE_SIZE) {
$page = $client->post('/api/operation/readmails', [
'emailAddress' => 'info@example.com',
'path' => ['Facturen', '2026'],
'skip' => $skip,
'take' => PAGE_SIZE,
'mailSort' => 1, // NewToOld
]);
if ($page['status'] !== 0) {
throw new RuntimeException('ReadMails failed: ' . $page['error']);
}
array_push($all, ...$page['emails']);
if (count($page['emails']) < PAGE_SIZE) {
break; // last page
}
}
echo count($all), ' emails read', PHP_EOL;
PAGE_SIZE = 250 # the maximum per call
all_emails = []
skip = 0
while True:
page = client.post("/api/operation/readmails", {
"emailAddress": "info@example.com",
"path": ["Facturen", "2026"],
"skip": skip,
"take": PAGE_SIZE,
"mailSort": 1, # NewToOld
})
if page["status"] != 0:
raise RuntimeError(f"ReadMails failed: {page['error']}")
all_emails.extend(page["emails"])
if len(page["emails"]) < PAGE_SIZE:
break # last page
skip += PAGE_SIZE
print(len(all_emails), "emails read")
const PAGE_SIZE = 250; // the maximum per call
const all = [];
for (let skip = 0; ; skip += PAGE_SIZE) {
const page = await client.post('/api/operation/readmails', {
emailAddress: 'info@example.com',
path: ['Facturen', '2026'],
skip,
take: PAGE_SIZE,
mailSort: 1, // NewToOld
});
if (page.status !== 0) throw new Error(`ReadMails failed: ${page.error}`);
all.push(...page.emails);
if (page.emails.length < PAGE_SIZE) break; // last page
}
console.log(all.length, 'emails read');
const pageSize = 250 // the maximum per call
var all []json.RawMessage
for skip := 0; ; skip += pageSize {
var page struct {
Status int `json:"status"`
Error string `json:"error"`
Emails []json.RawMessage `json:"emails"`
}
err := client.Post("/api/operation/readmails", map[string]any{
"emailAddress": "info@example.com",
"path": []string{"Facturen", "2026"},
"skip": skip,
"take": pageSize,
"mailSort": 1, // NewToOld
}, &page)
if err != nil {
return err
}
if page.Status != 0 {
return fmt.Errorf("ReadMails failed: %s", page.Error)
}
all = append(all, page.Emails...)
if len(page.Emails) < pageSize {
break // last page
}
}
fmt.Println(len(all), "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.
senderEmailAddress
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.
datedatetime
When the message was sent, as the wall-clock time of the sender. Can be null for older messages.
textstring
The text of this message only.
inlineImagesAttachment[]
The images that are part of the text of this message. You can send them back in a new mail; see Sending mail.
attachmentsAttachment[]
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:
<img src='cid:AAMkATT2…'>
Met vriendelijke groet,
Jan Jansen
**text**
Bold.
_text_
Italic.
__text__
Underlined.
<img src='cid:…'>
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/getattachmentfree
Request
emailAddressstring required
The connected mailbox.
emailIdstring required
The uniqueId of the mail.
attachmentIdstring required
The id of the attachment, from attachments or inlineImages.
# 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
// emailId = Email.UniqueId and attachmentId = Attachment.Id, both from ReadMails.
byte[] data = await client.PostAsync<byte[]>("/api/operation/getattachment", new
{
emailAddress = "info@example.com",
emailId = email.UniqueId,
attachmentId = attachment.Id
});
// The response is a JSON string with base64; System.Text.Json decodes it into byte[].
await File.WriteAllBytesAsync(Path.GetFileName(attachment.Filename), data);
// emailId = the email's uniqueId and attachmentId = the attachment's id, both from ReadMails.
JsonNode data = client.post("/api/operation/getattachment", Map.of(
"emailAddress", "info@example.com",
"emailId", email.get("uniqueId").asText(),
"attachmentId", attachment.get("id").asText()));
// The response is a JSON string with base64.
Files.write(Path.of(attachment.get("filename").asText()).getFileName(),
Base64.getDecoder().decode(data.asText()));
// emailId = the email's uniqueId and attachmentId = the attachment's id, both from ReadMails.
$base64 = $client->post('/api/operation/getattachment', [
'emailAddress' => 'info@example.com',
'emailId' => $email['uniqueId'],
'attachmentId' => $attachment['id'],
]);
// The response is a JSON string with base64.
file_put_contents(basename($attachment['filename']), base64_decode($base64, true));
import base64
import os
# emailId = the email's uniqueId and attachmentId = the attachment's id, both from ReadMails.
data = client.post("/api/operation/getattachment", {
"emailAddress": "info@example.com",
"emailId": email["uniqueId"],
"attachmentId": attachment["id"],
})
# The response is a JSON string with base64.
with open(os.path.basename(attachment["filename"]), "wb") as file:
file.write(base64.b64decode(data))
import { writeFile } from 'node:fs/promises';
import { basename } from 'node:path';
// emailId = the email's uniqueId and attachmentId = the attachment's id, both from ReadMails.
const base64 = await client.post('/api/operation/getattachment', {
emailAddress: 'info@example.com',
emailId: email.uniqueId,
attachmentId: attachment.id,
});
// The response is a JSON string with base64.
await writeFile(basename(attachment.filename), Buffer.from(base64, 'base64'));
// emailId = the email's uniqueId and attachmentId = the attachment's id, both from ReadMails.
// The response is a JSON string with base64; decoding into []byte turns it back into bytes.
var data []byte
err := client.Post("/api/operation/getattachment", map[string]any{
"emailAddress": "info@example.com",
"emailId": mail.UniqueID,
"attachmentId": file.ID,
}, &data)
if err != nil {
return err
}
if err := os.WriteFile(filepath.Base(file.Filename), data, 0o600); err != nil {
return err
}
Response
The response is not an object, but one JSON string with the contents as base64:
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/checkpath1 action
Request
emailAddressstring required
The connected mailbox.
pathstring[] required
The folder, with at least one name. How a path works is explained with Reading mail under Folders.
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/movemail1 action
Request
emailAddressstring required
The connected mailbox.
messageIdstring required
The uniqueId of the mail.
pathstring[] required
The folder the mail goes to, with at least one name.
readStatusbool
true also marks the mail as read, false as unread. When you leave the field out, the read status does not change.
# 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.
var moved = await client.PostAsync<MoveMailResponse>("/api/operation/movemail", new
{
emailAddress = "info@example.com",
messageId = email.UniqueId,
path = new[] { "Verwerkt" },
readStatus = true // optional: also mark as read; leave out to keep the read status as it is
});
if (moved.Status != ResponseStatus.Success)
throw new InvalidOperationException($"MoveMail failed: {moved.Error}");
// A moved mail can get a new id. Use this one from now on, not email.UniqueId.
string newId = moved.UniqueId;
record MoveMailResponse(ResponseStatus Status, string? Error, string UniqueId);
JsonNode moved = client.post("/api/operation/movemail", Map.of(
"emailAddress", "info@example.com",
"messageId", email.get("uniqueId").asText(),
"path", List.of("Verwerkt"),
"readStatus", true)); // optional: also mark as read; leave out to keep the read status as it is
if (moved.get("status").asInt() != 0)
throw new IllegalStateException("MoveMail failed: " + moved.get("error").asText());
// A moved mail can get a new id. Use this one from now on, not the id you moved.
String newId = moved.get("uniqueId").asText();
$moved = $client->post('/api/operation/movemail', [
'emailAddress' => 'info@example.com',
'messageId' => $email['uniqueId'],
'path' => ['Verwerkt'],
'readStatus' => true, // optional: also mark as read; leave out to keep the read status as it is
]);
if ($moved['status'] !== 0) {
throw new RuntimeException('MoveMail failed: ' . $moved['error']);
}
// A moved mail can get a new id. Use this one from now on, not $email['uniqueId'].
$newId = $moved['uniqueId'];
moved = client.post("/api/operation/movemail", {
"emailAddress": "info@example.com",
"messageId": email["uniqueId"],
"path": ["Verwerkt"],
"readStatus": True, # optional: also mark as read; leave out to keep the read status as it is
})
if moved["status"] != 0:
raise RuntimeError(f"MoveMail failed: {moved['error']}")
# A moved mail can get a new id. Use this one from now on, not email["uniqueId"].
new_id = moved["uniqueId"]
const moved = await client.post('/api/operation/movemail', {
emailAddress: 'info@example.com',
messageId: email.uniqueId,
path: ['Verwerkt'],
readStatus: true, // optional: also mark as read; leave out to keep the read status as it is
});
if (moved.status !== 0) throw new Error(`MoveMail failed: ${moved.error}`);
// A moved mail can get a new id. Use this one from now on, not email.uniqueId.
const newId = moved.uniqueId;
var moved struct {
Status int `json:"status"`
Error string `json:"error"`
UniqueID string `json:"uniqueId"`
}
err := client.Post("/api/operation/movemail", map[string]any{
"emailAddress": "info@example.com",
"messageId": mail.UniqueID,
"path": []string{"Verwerkt"},
"readStatus": true, // optional: also mark as read; leave out to keep the read status as it is
}, &moved)
if err != nil {
return err
}
if moved.Status != 0 {
return fmt.Errorf("MoveMail failed: %s", moved.Error)
}
// A moved mail can get a new id. Use this one from now on, not mail.UniqueID.
newID := moved.UniqueID
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.
var marked struct {
Status int `json:"status"`
Error string `json:"error"`
}
err := client.Post("/api/operation/setreadstatus", map[string]any{
"emailAddress": "info@example.com",
"emailId": mail.UniqueID,
"readStatus": true, // true = read, false = unread
}, &marked)
if err != nil {
return err
}
if marked.Status != 0 {
return fmt.Errorf("SetReadStatus failed: %s", marked.Error)
}
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
200OK
The request has been processed. For operations, still look at status.
401Unauthorized
When logging in: the code or the security key is wrong. For other calls: the token is missing or has expired; log in again.
403Forbidden
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.
500Server error
Something went wrong on our side. Try again later.
The status field
0Success
The operation succeeded.
1Failure
The operation failed. error holds the reason.
2Unauthorized
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.
1One action
Sending mail, creating a draft, reading mail, checking a folder, moving a mail and setting the read status.
0Free
Logging in, connecting a mailbox, getting attachments, and every call that did not succeed.
An example
1Read
You read 250 mails in one call.
0Attachments
You get the attachments of all those mails.
5Move
You move five mails to another folder and mark them as read while doing so.
6Total
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.