Verstuur mail, zet concepten klaar en lees en verwerk inkomende mail uit de mailbox van je klant, via één HTTP-API voor Microsoft 365 en Google.
Je sleutels zijn wachtwoorden
De security key en het sleutelbestand geven samen toegang tot elke mailbox die aan je applicatie is gekoppeld. Bewaar ze buiten je broncode en geef alleen je eigen server er toegang toe.
Klaar voor AI-assistenten
Laat je de koppeling liever schrijven door een AI-assistent? Deze documentatie staat er ook in een vorm die assistenten goed kunnen lezen. Zie Bouwen met AI.
Zo werkt het
Inloggen. De applicatie logt in met de application id, de security key en een code uit het sleutelbestand. De applicatie krijgt een token dat 10 minuten geldig is. Zie Inloggen.
Een mailbox koppelen. De eigenaar van de mailbox geeft één keer toestemming bij Microsoft of Google. Zie Mailbox koppelen.
Operaties aanroepen. Met het token verstuur, lees en verplaats je mail in die mailbox.
Wat je nodig hebt
Alle drie vind je bij je applicatie in Mailbox Connector.
application id
Het id van je applicatie, bijvoorbeeld 3f2b8c1e-7a4d-4e9b-9c55-0d6a1b2e4f70.
security key
Een geheime sleutel die bij de applicatie hoort.
security.mckey
Het sleutelbestand: 1.000.000 regels met codes. Je downloadt het als {application id}.mckey; in deze documentatie heet het security.mckey.
Afspraken
Het adres van de API is https://mailboxconnector.com.
Verzoeken en antwoorden zijn JSON, met veldnamen in camelCase.
Elke aanroep na het inloggen stuurt het token mee in de header Authorization: Bearer ….
Keuzewaarden zijn getallen. Bij elk veld staat welk getal wat betekent.
Een bijlage is base64 in een JSON-string.
Datums zijn ISO 8601. Bij een mail is dat de kloktijd van de afzender, zonder tijdzone; zie Mails lezen.
De voorbeelden
Kies bovenin een codeblok je taal. De keuze geldt voor alle blokken en wordt onthouden. De voorbeelden op de volgende pagina's gebruiken deze instellingen:
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 met curl en jq.
C#
.NET 6 of hoger, zonder extra pakketten.
Java
Java 17 of hoger, met Jackson voor JSON.
PHP
PHP 8.1 of hoger, met de cURL-extensie.
Python
Python 3.8 of hoger, met requests.
Node.js
Node.js 18 of hoger, zonder extra pakketten.
Go
Go 1.20 of hoger, alleen de standaardbibliotheek.
Bouwen met een AI-assistent
Mailbox Connector is voorbereid op AI-assistenten zoals Claude, ChatGPT en Copilot. Je geeft je assistent één adres. Daarna weet de assistent hoe de API werkt en kan die de koppeling schrijven in jouw programmeertaal.
Hoe het werkt
Een AI-assistent leest een pagina als deze slecht: die is gemaakt voor mensen in een browser. Daarom staat dezelfde documentatie er ook als platte tekst, en staan de aanroepen in een beschrijving die programma's kunnen lezen. Het zijn gewone bestanden; je kunt ze zelf openen.
De beschrijving van elke aanroep in OpenAPI-formaat, voor codegeneratoren en voor assistenten die daarmee werken.
De tekstbestanden zijn in het Engels. Je assistent antwoordt gewoon in jouw taal.
Zo gebruik je het
Kies hieronder je programmeertaal.
Kopieer de opdracht en geef die aan je assistent. Pas de laatste regel aan naar wat je wilt bouwen.
Vul in het resultaat je eigen instellingen in en test het.
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.
Geef je sleutels nooit aan een assistent
Plak je security key of de inhoud van je sleutelbestand nooit in een gesprek met een AI-assistent. De assistent heeft ze niet nodig om de code te schrijven: de code leest ze uit je configuratie.
Controleer het resultaat
Een assistent schrijft meestal goede code, maar niet altijd. Kijk in elk geval of het resultaat dit doet:
Het token wordt hergebruikt, en er wordt niet voor elke aanroep opnieuw ingelogd.
Het sleutelbestand wordt niet in zijn geheel in het geheugen geladen.
Bij een 401 tijdens het inloggen wordt een nieuwe challenge opgehaald, met hooguit drie pogingen.
Na elke operatie wordt het veld status gecontroleerd.
Twijfel je, vergelijk het dan met de complete client: die is getest.
Inloggen
Inloggen gaat in drie stappen: je haalt een challenge op, zoekt de bijbehorende code op in je sleutelbestand en wisselt die code in voor een token.
Eén applicatie is één koppeling
Een applicatie in Mailbox Connector is bedoeld voor één installatie van jouw software: een site, met hooguit een paar batches ernaast. Loggen meer processen tegelijk in, dan zitten ze elkaar in de weg. Na meer dan vijf foute codes staat de applicatie 5 minuten stil.
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
200Gelukt
Het antwoord bevat de challenge.
204Geen sleutelbestand
Voor deze applicatie is nog geen sleutelbestand aangemaakt. Probeer het over een paar minuten opnieuw.
401Onbekend
Er bestaat geen applicatie met dit id.
Stap 2: de code opzoeken
De challenge is een regelnummer in je sleutelbestand, geteld vanaf 0. Challenge 0 is dus de eerste regel: je slaat zoveel regels over als de challenge aangeeft en leest de volgende.
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
}
De functie die de regel leest zonder het hele bestand in te laden, staat op Sleutelbestand lezen.
Stap 3: inloggen
POST/api/login
codestring verplicht
De regel uit het sleutelbestand die bij de challenge hoort.
applicationIdstring verplicht
Het id van je applicatie.
securityKeystring verplicht
De security key van je applicatie.
# 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);
Het antwoord bevat het token. Eerdere fouten zijn hiermee gewist.
401Geweigerd
De code of de security key klopt niet, of de applicatie bestaat niet. Dit telt als fout. Haal een nieuwe challenge op voordat je het opnieuw probeert.
403Geblokkeerd
Er waren meer dan vijf fouten. Wacht 5 minuten.
Het token gebruiken
Stuur het token mee met elke aanroep:
http
POST /api/operation/sendmail HTTP/1.1
Host: mailboxconnector.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNmMmI4YzFlLTdhNGQ…
Content-Type: application/json
Bewaar het token en gebruik het opnieuw tot een minuut voordat het verloopt. Log niet voor elke aanroep opnieuw in.
Het token bevat de rechten die je applicatie had op het moment van inloggen. Rechten die erbij komen doordat een mailbox wordt gekoppeld, gelden vanaf de volgende login.
Het sleutelbestand is ongeveer 10 MB groot. Bij elke login heb je er precies één regel uit nodig. Lees die regel zonder het hele bestand in het geheugen te laden.
Het bestand
regels
1.000.000, één code per regel.
code
6 tot 12 tekens: letters en cijfers.
regeleinde
Een line feed (\n), ook na de laatste regel.
tekenset
ASCII, zonder BOM.
De regel vinden
De regels zijn niet even lang, dus je kunt niet naar een vaste plek springen. De zuinige manier is: lees het bestand in blokken in één buffer, tel de regeleinden, en maak alleen van de gevraagde regel een 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)
}
Wat het scheelt
Deze functie gebruikt één buffer van 64 KB, welke regel je ook vraagt. Het hele bestand inlezen en in regels splitsen kost 40 tot 70 MB per login.
Liever niet
Het hele bestand inlezen, met bijvoorbeeld File.ReadAllLines, file(), readlines() of readFileSync().split().
Het bestand in je repository zetten. Het is een geheim. Bovendien kan Git de regeleinden omzetten; de voorbeelden halen daarom een eventuele \r van de regel af.
De inhoud in het geheugen bewaren om het sneller te maken. Je leest één regel per tien minuten; sneller hoeft het niet, en het geheim blijft zo op schijf.
Limieten en opnieuw proberen
De challenge is een teller. Als je weet hoe die werkt, weet je ook waarom twee processen elkaar kunnen storen en hoe je dat opvangt.
Hoe de challenge werkt
Elke applicatie heeft één teller. De challenge ophalen geeft de huidige stand en verandert niets.
Elke inlogpoging met de juiste security key zet de teller één verder, of de code nu goed of fout was. Een poging met een foute security key verandert niets.
Twee processen die tegelijk een challenge ophalen, krijgen dus hetzelfde getal. De eerste die inlogt slaagt. De tweede krijgt een 401, want de teller staat inmiddels één verder.
De blokkade
401Foute code
Telt als één fout voor de applicatie, vanaf welk adres die ook komt.
401Foute security key
Telt als één fout voor het adres waar die vandaan komt. De applicatie wordt er niet door geblokkeerd.
403Meer dan 5 fouten
Inloggen is geblokkeerd tot 5 minuten na de laatste fout. Foute codes blokkeren de applicatie; foute security keys alleen het adres waar ze vandaan kwamen.
200Geslaagde login
Wist de fouten van de applicatie. Zolang er tussendoor iemand slaagt, loopt de teller dus niet op.
Wat je client moet doen
Hergebruik het token. Het is 10 minuten geldig. Log pas opnieuw in als het binnen een minuut verloopt.
Eén login tegelijk per proces. Laat gelijktijdige aanroepen op dezelfde login wachten in plaats van elk zelf in te loggen.
Bij een 401: wacht even en begin opnieuw. Wacht een willekeurige tijd tussen 0,2 en 1 seconde, haal een nieuwe challenge op en log opnieuw in. Stop na drie pogingen.
Bij een 403: stop. Wacht 5 minuten. Blijven proberen helpt niet.
Deel het token waar dat kan. Processen op dezelfde server kunnen één token delen; dan logt er maar één in. De PHP-client doet dat met een bestand.
Loggen meerdere processen op hetzelfde moment in, dan slaagt er één en krijgt de rest een 401. Met een site en drie batches blijf je daarmee ruim onder de grens. Vier batches kan, maar houd het daarbij: met meer processen loop je het risico dat ze samen meer dan vijf fouten achter elkaar maken, en dan staat de applicatie 5 minuten stil.
Spreid je batches
Start batches niet allemaal op hetzelfde tijdstip. Een batch die om :00 start en een die om :02 start, komen elkaar bij het inloggen niet tegen.
Complete client
Eén bestand per taal dat inlogt, het token hergebruikt, botsingen opvangt en operaties aanroept. Kopieer het en vul je eigen instellingen in.
#!/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)
}
Een andere taal, of wil je de client op maat? Een AI-assistent schrijft die voor je; zie Bouwen met AI.
Gebruik
De voorbeelden bij de operaties gaan uit van deze 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 taal
cURL
Roep mc_login aan vóór een aanroep, in het script zelf en niet binnen $( … ). De functie logt alleen in als het token ontbreekt of bijna verloopt.
C#
Registreer de client als singleton, zodat alle aanroepen in het proces hetzelfde token gebruiken.
Java
Maak één instantie en deel die. post geeft een JsonNode van Jackson terug.
PHP
PHP begint elk verzoek met een leeg geheugen. De client bewaart het token daarom in een bestand in de tijdelijke map, met een lock. Alle PHP-processen op de server delen zo één token.
Python
Maak één instantie en deel die. De client is veilig voor meerdere threads.
Node.js
Maak één instantie en deel die. Gelijktijdige aanroepen wachten op dezelfde login.
Go
Maak één Client en deel die; de Client is veilig voor meerdere goroutines. Post vult het resultaat dat je meegeeft.
Mailbox koppelen
Voordat je applicatie een mailbox kan gebruiken, geeft de eigenaar één keer toestemming bij Microsoft of Google. Jij start dat met een koppelverzoek.
Het verloop
Controleer of de mailbox al gekoppeld is.
Zo niet: maak een koppelverzoek aan. Je krijgt een id terug.
Stuur de gebruiker naar https://mailboxconnector.com/connect/{id}.
De gebruiker logt daar in bij Microsoft of Google, met de mailbox zelf, en geeft toestemming.
Daarna komt de gebruiker terug op jouw returnUrl. Controleer dan opnieuw of de mailbox gekoppeld is.
Koppeling controleren
POST/api/connectionrequest/checkgratis
desiredEmailAddressstring verplicht
Het adres van de mailbox.
needsSendMailbool
Je wilt mail versturen.
needsCreateDraftbool
Je wilt concepten aanmaken.
needsReadMailbool
Je wilt mails lezen, bijlagen ophalen en mappen controleren.
needsMoveMailbool
Je wilt mails verplaatsen en de leesstatus zetten.
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.")
}
Antwoord
json
{
"connectionStatus": 2
}
De waarden van connectionStatus:
0NotConfigured
De mailbox is niet aan je applicatie gekoppeld. Maak een koppelverzoek aan.
1MissingPermissions
De mailbox is gekoppeld, maar niet voor alles wat je vraagt. Maak een nieuw koppelverzoek aan met de rechten die je nodig hebt.
2Connected
De mailbox is gekoppeld met alle gevraagde rechten.
Koppelverzoek aanmaken
POST/api/connectionrequest/creategratis
Dezelfde velden als bij het controleren, met daarbij:
returnUrlstring verplicht
De pagina in jouw applicatie waar de gebruiker na het koppelen op terugkomt.
logoUrlstring
Het logo van jouw applicatie, voor op de koppelpagina.
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)
Het id van het koppelverzoek. Hiermee stuur je de gebruiker naar de koppelpagina.
Goed om te weten
Een koppelverzoek is 30 minuten geldig. Maak het aan op het moment dat de gebruiker gaat koppelen, niet vooraf.
De gebruiker logt in als de mailbox zelf. Bij inloggen met een ander account wordt er niets gekoppeld; de gebruiker kan het dan opnieuw proberen.
Moet een beheerder toestemming geven? Dan logt eerst de beheerder in en geeft die toestemming namens de organisatie. Daarna logt de gebruiker zelf in, met hetzelfde koppelverzoek of een nieuw.
Microsoft 365 of Google wordt bepaald aan de hand van het adres. Je hoeft dat niet op te geven.
Nieuwe rechten gelden vanaf de volgende login van je applicatie. Het token dat je al had, kent ze nog niet.
Mail versturen
Verstuurt een mail vanuit een gekoppelde mailbox. De mail komt ook in de verzonden items van die mailbox te staan, tenzij je saveToSentItems op false zet.
POST/api/operation/sendmail1 actie
Verzoek
senderEmailAddress verplicht
De gekoppelde mailbox waaruit je verstuurt.
toEmailAddress[] verplicht
De ontvangers.
ccEmailAddress[]
Ontvangers in kopie.
bccEmailAddress[]
Ontvangers in blinde kopie.
subjectstring
Het onderwerp.
bodystring
De inhoud, als HTML.
attachmentsMailAttachment[]
De bijlagen.
saveToSentItemsboolean
Of er een kopie in de verzonden items van de verzendende mailbox komt. Laat je het weg of zet je true, dan gebeurt dat (de standaard); false voor mails die niemand daar terug hoeft te vinden, zoals inlogcodes. Alleen bij versturen, niet bij concepten.
EmailAddress
emailstring verplicht
Het e-mailadres.
aliasstring
De naam die de ontvanger ziet. Laat je die weg, dan wordt het deel vóór het apenstaartje gebruikt.
MailAttachment
filenamestring verplicht
De bestandsnaam.
contentTypestring verplicht
Het type, bijvoorbeeld application/pdf.
datastring verplicht
De inhoud van het bestand, als base64.
contentIdstring
Laat leeg voor een gewone bijlage. Vul je het in, dan staat de afbeelding in de tekst van de mail. Zie Afbeeldingen in de tekst hieronder.
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")
Afbeeldingen in de tekst
Een afbeelding die in de tekst van de mail moet staan, zoals een logo of een schermafbeelding, stuur je mee als bijlage met een contentId. In de body wijs je ernaar met cid: en dat id.
Beantwoord je een mail en wil je de afbeeldingen uit die mail meesturen? In de text van een bericht staat op de plek van elke afbeelding <img src='cid:ID'>; die afbeeldingen staan in inlineImages. Haal de inhoud op met Bijlage ophalen, stuur de afbeelding mee met een eigen contentId, en zet in je nieuwe tekst op die plek <img src="cid:..."> met dat id.
Niet gevuld bij versturen. Bij Concept aanmaken staat hier het id van het concept.
retryAfterSecondsint
Alleen bij de fout RateLimited door onze eigen limieten: na hoeveel seconden de mail verstuurd kan worden. Staat ook in de HTTP-header Retry-After.
Limieten en spamcontrole
Mailbox Connector stopt een applicatie die te veel verstuurt, of iets dat op spam lijkt, voordat Microsoft of Google de mailbox blokkeren. De controle draait helemaal op onze eigen servers: de inhoud van een mail wordt alleen tijdens het versturen in het geheugen bekeken en nooit bewaard.
Per mailbox
Over alle applicaties die met die mailbox versturen samen.
20
Per minuut.
300
Per uur.
1.500
Per 24 uur.
Per applicatie
5.000
Mails per 24 uur, over al haar mailboxen samen.
100
Ontvangers per mail (to, cc en bcc samen). Meer geeft TooManyRecipients.
Nieuwe applicaties beginnen de eerste 7 dagen op de helft van deze limieten.
Boven een limiet wordt de mail niet verstuurd: status is 1, error is RateLimited en retryAfterSeconds zegt na hoeveel seconden hij weer past. Hetzelfde getal staat in de HTTP-header Retry-After. Wacht zo lang en verstuur de mail opnieuw; eerder wordt hij op dezelfde manier geweigerd. Ook de mailprovider kan RateLimited geven; wacht dan een minuut.
Grotere runs, zoals facturen rond de 1e van de maand: neem contact met ons op. Wij kunnen de limieten van je applicatie verhogen.
Grote runs, zoals facturen rond de 1e
De spamcontrole leert het ritme van je applicatie: vanaf de tweede maand is een run zoals de vorige gewoon normaal, ook naar dezelfde klanten. De allereerste run van een nieuwe applicatie kan voor ons gemarkeerd worden, maar wordt niet alleen om zijn omvang geweigerd. De limieten gelden wel: 1.000 facturen uit één mailbox duren bij 300 per uur ruim 3 uur. Zet de mails daarom in een wachtrij in plaats van ze in één lus te versturen, en zet een mail bij RateLimited terug met "niet voor" = nu + retryAfterSeconds, in plaats van de hele run te laten wachten. Meer nodig? Vraag ons vooraf de limieten van je applicatie te verhogen.
De spamcontrole
Elke mail krijgt een score op basis van de inhoud (bekende spam- en phishingzinnen in het Nederlands, Engels, Duits en Frans), de opbouw (links die een ander adres tonen dan waar ze heen gaan, verkorte links, links naar een IP-adres, gevaarlijke bijlagen zoals .exe) en het verzendpatroon van je applicatie vergeleken met haar eigen normaal, inclusief maandelijkse en jaarlijkse runs.
Een mail die maar een beetje verdacht is, wordt verstuurd en voor ons gemarkeerd.
Een duidelijk verdachte mail wordt geweigerd met SuspectedSpam. Daarvoor moeten de inhoud van de mail én het verzendpatroon verdacht zijn; een van beide alleen weigert nooit een mail.
Na 3 weigeringen binnen 24 uur wordt het verzenden voor de applicatie gepauzeerd: elke mail krijgt SendingPaused tot wij het samen met jou hebben bekeken en de pauze opheffen. Lezen en verplaatsen werken gewoon.
Concept aanmaken
Zet een mail klaar in de concepten van een gekoppelde mailbox, zonder die te versturen. Handig als een mens er nog iets aan toevoegt: jouw applicatie zet de offerte klaar, de verkoper schrijft er zelf een begeleidende tekst bij en verstuurt de mail.
Naast status en error bevat het antwoord emails. Elke mail heeft:
uniqueIdstring
Het id van de mail. Je gebruikt het bij bijlagen ophalen, verplaatsen en de leesstatus zetten.
conversationIdstring
Het gesprek waar de mail bij hoort.
pathstring[]
Waar de mail staat, net zo geschreven als de paden waaruit je leest en waarnaar je verplaatst: null voor de inbox, ["Facturen", "2026"] voor een map in de inbox (bij Google: het label Facturen/2026), en [] als geen pad ernaar wijst, zoals de verzonden items of het archief. Handig als je leest op filterUniqueId of conversationId: die vinden mails in elke map. Zie Mappen.
receiveddatetime
Het moment van ontvangst, als kloktijd van de afzender en zonder tijdzone. Een mail die om 14:56 UTC binnenkwam van een Nederlandse afzender in de zomer, heeft 16:56.
senderEmailAddress
De afzender: email en alias.
to, cc, bccEmailAddress[]
De ontvangers.
subjectstring
Het onderwerp.
bodystring
De volledige inhoud, als ruwe HTML.
isReadbool
Of de mail gelezen is.
attachmentsAttachment[]
Alle bijlagen, ook afbeeldingen die in de tekst staan. Per bijlage: id, filename, contentType en contentId. De inhoud haal je op met Bijlage ophalen.
Nieuwste eerst. Gebruik deze, tenzij je een reden hebt voor de andere.
0OldToNew
Oudste eerst. Bij Google wordt hiervoor de hele map doorgelezen. Gebruik het alleen met filters die het aantal mails klein houden, of op mappen die je leeg houdt door verwerkte mails te verplaatsen.
Met skip en take blader je door een map, 250 mails per keer:
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")
Verwerken in een batch
Komt er nieuwe mail binnen terwijl je bladert, dan schuiven de pagina's op. Voor een batch werkt dit beter: lees de eerste pagina, verwerk elke mail, verplaats die naar een andere map en lees daarna opnieuw vanaf het begin, tot de map leeg is.
Mappen
Een pad is een lijst met mapnamen, van boven naar beneden. Zonder pad bedoel je de inbox.
["Verwerkt"]
De map Verwerkt in de inbox.
["Facturen", "2026"]
De map 2026 in de map Facturen.
Microsoft 365: het pad begint in de inbox en gebruikt de namen zoals de gebruiker ze ziet: ["Verwerkt"] is de map Verwerkt in de inbox, in welke taal de mailbox ook is. Een pad dat met de inbox zelf begint (["Inbox", "Verwerkt"], of ["Postvak IN", "Verwerkt"] in een Nederlandse mailbox) komt bij dezelfde map uit.
Google: het pad is een label. ["Facturen", "2026"] is het label Facturen/2026. Een mail met meer labels: gelezen uit een label is zijn path dat label; gelezen op id of gesprek is het null zolang de mail ook in de inbox staat, en anders zijn diepste label.
Berichten in een mail
Een mail is vaak een hele draad: een antwoord met daaronder het oorspronkelijke bericht, of een doorgestuurde mail. Mailbox Connector knipt die draad voor je op in losse berichten, elk met een afzender, een datum en leesbare tekst.
Wat je krijgt
Elke mail uit Mails lezen heeft een lijst messages, met het nieuwste bericht eerst. Het eerste bericht is wat de afzender zelf schreef; daarna volgen de berichten die eronder hingen.
senderEmailAddress
Wie het bericht schreef. Bij het eerste bericht is dat de afzender van de mail. Bij oudere berichten komt het uit de kop boven het bericht, en kan het null zijn als die kop geen afzender noemt.
datedatetime
Wanneer het bericht is verstuurd, als kloktijd van de afzender. Kan null zijn bij oudere berichten.
textstring
De tekst van alleen dit bericht.
inlineImagesAttachment[]
De afbeeldingen die in de tekst van dit bericht staan. Je kunt ze in een nieuwe mail terugsturen; zie Mail versturen.
attachmentsAttachment[]
De gewone bijlagen van de mail. Die staan altijd bij het eerste bericht.
De tekst
De HTML is omgezet naar tekst die je direct kunt tonen of doorzoeken:
text
Beste Piet,
Hierbij de offerte. De planning staat in dit schema:
<img src='cid:AAMkATT2…'>
Met vriendelijke groet,
Jan Jansen
**tekst**
Vet.
_tekst_
Cursief.
__tekst__
Onderstreept.
<img src='cid:…'>
Een afbeelding, op de plek waar die in het bericht staat. Na cid: staat het id van de bijlage in inlineImages.
Regels en alinea's staan zoals je ze in je mailprogramma ziet: een lege regel waar het mailprogramma ruimte tussen alinea's toont, een enkele regelovergang waar de regels op elkaar aansluiten.
Afbeeldingen bij het juiste bericht
Een afbeelding in de tekst hoort bij het bericht waarin die staat, ook als dat bericht drie antwoorden diep zit. Je ziet dus in welk bericht van de draad een schema of schermafbeelding is meegestuurd. De inhoud haal je op met Bijlage ophalen; dat kost geen actie.
Kleine plaatjes uit handtekeningen, zoals pictogrammen van sociale media, worden weggelaten.
Wat wordt weggelaten
Regels als "Verzonden vanaf mijn iPhone".
Regels met een disclaimer of een vertrouwelijkheidsverklaring.
De kop boven een aangehaald bericht (Van, Verzonden, Aan, Onderwerp) en de tekens waarmee een citaat wordt aangegeven.
De grenzen
Zo goed mogelijk, niet gegarandeerd
Mailprogramma's schrijven een draad elk op hun eigen manier. De herkenning werkt voor de gangbare vormen in het Nederlands, Engels, Duits en Frans, en wordt uitgebreid waar dat nodig blijkt. Reken er niet op dat elke draad perfect wordt opgeknipt.
Van een link blijft de tekst over, niet het adres erachter.
Opsommingen en tabellen worden gewone regels.
Heb je de opmaak nodig, gebruik dan body: daar staat de ruwe HTML van de hele mail.
Bijlage ophalen
Haalt de inhoud van één bijlage op. Mails lezen geeft alleen de naam en het type van een bijlage; de inhoud haal je hier op als je die nodig hebt.
POST/api/operation/getattachmentgratis
Verzoek
emailAddressstring verplicht
De gekoppelde mailbox.
emailIdstring verplicht
Het uniqueId van de mail.
attachmentIdstring verplicht
Het id van de bijlage, uit attachments of 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
}
Antwoord
Het antwoord is geen object, maar één JSON-string met de inhoud als base64:
Heeft je applicatie geen leesrecht op de mailbox, dan is het antwoord leeg.
Gaat het ophalen bij de mailprovider mis, dan krijg je HTTP 500.
Eerst ophalen, dan verplaatsen
Een mail kan bij het verplaatsen een nieuw id krijgen. Haal bijlagen dus op voordat je de mail verplaatst, of gebruik daarna het uniqueId uit het antwoord van Mail verplaatsen.
Map controleren
Controleert of een map bestaat in een gekoppelde mailbox. Er wordt niets aangemaakt.
POST/api/operation/checkpath1 actie
Verzoek
emailAddressstring verplicht
De gekoppelde mailbox.
pathstring[] verplicht
De map, met minstens één naam. Hoe een pad werkt, staat bij Mails lezen onder Mappen.
Verplaatst een mail naar een map. Bestaat de map nog niet, dan wordt die aangemaakt. Je kunt de mail in dezelfde aanroep als gelezen markeren.
POST/api/operation/movemail1 actie
Verzoek
emailAddressstring verplicht
De gekoppelde mailbox.
messageIdstring verplicht
Het uniqueId van de mail.
pathstring[] verplicht
De map waar de mail naartoe gaat, met minstens één naam.
readStatusbool
true markeert de mail ook als gelezen, false als ongelezen. Laat je het veld weg, dan verandert de leesstatus niet.
# 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
Bij Microsoft 365 krijgt een verplaatste mail een nieuw id; het oude werkt daarna niet meer. Gebruik voor alles wat je na het verplaatsen met de mail doet het uniqueId uit dit antwoord.
Bij Google bestaan geen mappen, maar labels. Verplaatsen haalt de mail uit de inbox en uit de andere labels, en geeft de mail het label van het pad. De mail staat daarna dus op één plek, net als bij Microsoft 365.
Leesstatus zetten
Markeert een mail als gelezen of ongelezen, zonder die te verplaatsen. Wil je een mail verplaatsen én markeren, doe dat dan in één keer met Mail verplaatsen.
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)
}
Antwoord
json
{
"status": 0,
"error": null
}
Het antwoord bevat alleen status en error.
Statussen en fouten
Een aanroep kan op twee niveaus misgaan: de HTTP-status zegt of je verzoek is aangekomen en toegestaan, het veld status in het antwoord zegt of de operatie in de mailbox is gelukt. Controleer ze allebei.
HTTP-status
200OK
Het verzoek is verwerkt. Kijk bij operaties nog naar status.
401Unauthorized
Bij inloggen: de code of de security key klopt niet. Bij andere aanroepen: het token ontbreekt of is verlopen; log opnieuw in.
403Forbidden
Bij inloggen: de applicatie is 5 minuten geblokkeerd. Bij een operatie: geen enkele mailbox van je applicatie heeft het recht voor deze operatie. Is er net een mailbox gekoppeld, log dan opnieuw in.
500Server error
Er ging iets mis aan onze kant. Probeer het later opnieuw.
Het veld status
0Success
De operatie is gelukt.
1Failure
De operatie is mislukt. In error staat de reden.
2Unauthorized
Deze mailbox is niet aan je applicatie gekoppeld, of niet met het recht voor deze operatie. Zie Mailbox koppelen.
json
{
"status": 1,
"error": "RateLimited"
}
Het veld error
Bij status 1 staat in error een van deze redenen, als tekst:
InvalidRecipients
Een of meer adressen zijn geweigerd. Corrigeer de adressen; opnieuw proberen helpt niet.
MessageTooLarge
De mail is te groot. Verklein of verwijder bijlagen.
QuotaExceeded
De mailbox heeft de verzendlimiet bereikt of is vol. Probeer het later opnieuw.
RateLimited
Te veel mails in korte tijd: een limiet van Mailbox Connector of van de mailprovider. Wacht retryAfterSeconds seconden (of een minuut als dat leeg is) en probeer het opnieuw. Zie Limieten en spamcontrole.
TooManyRecipients
Meer dan 100 ontvangers in één mail. Splits de mail; opnieuw proberen helpt niet.
SuspectedSpam
De spamcontrole heeft de mail geweigerd. Verstuur hem niet ongewijzigd opnieuw: kijk naar de inhoud, de links en de bijlagen. Herhaalde weigeringen pauzeren het verzenden.
SendingPaused
Het verzenden is voor je applicatie gepauzeerd na herhaalde weigeringen door de spamcontrole. Neem contact met ons op; lezen en verplaatsen werken gewoon.
ProviderUnavailable
De mailprovider is tijdelijk niet bereikbaar. Probeer het later opnieuw.
ReauthRequired
De toestemming voor de mailbox is ingetrokken of verlopen. De mailbox moet opnieuw worden gekoppeld. Blijft dit 4 uur zo (en minstens 10 aanroepen), dan ontkoppelt Mailbox Connector de mailbox en mailt de beheerders van je account.
MailboxNotAvailable
De mailprovider heeft voor dit adres geen werkende mailbox (meer): bijvoorbeeld omdat de licentie is weggehaald, de gebruiker is verwijderd of de mailbox niet in de cloud staat. Opnieuw proberen helpt niet; herstel de mailbox bij de provider of koppel een andere. Blijft dit 4 uur zo (en minstens 10 aanroepen), dan ontkoppelt Mailbox Connector de mailbox en mailt de beheerders van je account.
UnexpectedError
Een andere fout, bijvoorbeeld een onbekend id of een leeg pad.
Acties en kosten
Je verbruik wordt geteld in acties. Hier staat wat een actie is, wat niets kost en hoe de bundels werken.
Wat telt
Elke geslaagde aanroep van een operatie is één actie, hoeveel mails er ook in het antwoord zitten.
1Eén actie
Mail versturen, concept aanmaken, mails lezen, map controleren, mail verplaatsen en leesstatus zetten.
0Gratis
Inloggen, een mailbox koppelen, bijlagen ophalen, en elke aanroep die niet is gelukt.
Een voorbeeld
1Lezen
Je leest 250 mails in één aanroep.
0Bijlagen
Je haalt van al die mails de bijlagen op.
5Verplaatsen
Je verplaatst vijf mails naar een andere map en markeert ze daarbij als gelezen.
6Totaal
Zes acties.
Bundels
Per maand zijn 50.000 acties inbegrepen.
Gebruik je er meer, dan komt er telkens een bundel van 50.000 acties bij voor 5 euro.
Let op hoe vaak je kijkt
Een aanroep die nul mails teruggeeft is ook geslaagd, en telt dus. Wie elke minuut de inbox leest, gebruikt ruim 43.000 acties per maand, ook als er niets binnenkomt. Elke vijf minuten kijken is voor de meeste toepassingen genoeg en kost minder dan 9.000 acties.