MailMigrata Public API

Programmatic access to mailbox migrations, bulk jobs, credential validation, and webhook callbacks. Version v1 on the Test API (https://test.api.migrata.systems).

Overview

The MailMigrata Public API lets you create and monitor IMAP mailbox migrations on behalf of your users. Typical flow:

  1. Validate the source and destination IMAP credentials with POST /v1/validate-credentials.
  2. Create a migration with POST /v1 (or a bulk migration via the bulk endpoint).
  3. Receive webhooks as the migration progresses, or poll GET /v1/{id}.

Base URL & Versioning

This page is served by the Test API. Sample requests below use https://test.api.migrata.systems.

EnvironmentBase URL
Test (this server)https://test.api.migrata.systems
QAhttps://qa.api.migrata.systems
Productionhttps://api.migrata.systems

All endpoints are prefixed with /v1. Breaking changes ship under a new version prefix; additive changes are made in place.

Authentication

Every request must include your API key in the X-Api-Key header. Keys are issued from your MailMigrata dashboard.

X-Api-Key: mm_live_3f9c…a01b
Content-Type: application/json
Keep keys secret. Treat API keys like passwords. Never expose them in browsers, mobile apps, or public repositories. Rotate immediately on suspected leak.

Scopes

Each API key is granted one or more scopes. The endpoint reference below shows the required scope.

ScopeGrants
credentials:validateValidate IMAP credentials without creating a migration.
migrations:createCreate single or bulk migrations.
migrations:readRead migration and bulk migration status.

Rate Limits

PolicyApplies toLimit
DefaultAll public endpoints60 requests / minute per API key (fallback: per client IP).
ValidationPOST /v1/validate-credentials10 requests / minute per API key (stricter, because it probes external servers).

When exceeded, the API returns HTTP 429 Too Many Requests. Back off and retry with exponential delay.

Errors

Errors return a stable JSON envelope and an appropriate HTTP status code.

{
  "code": "validation_failed",
  "message": "One or more fields are invalid.",
  "details": {
	"source": ["Source server, username and password are required."]
  }
}
HTTPCommon codesMeaning
400invalid_body, validation_failed, invalid_idThe request is malformed or fails validation.
401—Missing or invalid X-Api-Key.
403—The API key is valid but does not have the required scope.
404not_foundResource does not exist or is not owned by this key.
429—Rate limit exceeded.
500—Unexpected server error. Safe to retry with backoff.

POST/v1/validate-credentials

Scope: credentials:validateRate limit: validation

Performs an IMAP login attempt against the supplied source and/or destination mailbox. Recommended pre-flight before creating a migration, because incorrect credentials are the most common failure mode.

Request body

FieldTypeNotes
sourceMailboxEndpoint?Optional. At least one of source or destination is required.
destinationMailboxEndpoint?Optional. At least one of source or destination is required.

MailboxEndpoint

FieldTypeDefaultNotes
serverstring—IMAP hostname. May be left blank to trigger autoconfig from the email address.
portint993IMAP port.
usernamestring—Usually the full email address. Required.
passwordstring—IMAP password or app-password. Required. Sent in plaintext over TLS; never logged.
useSslbooltrueUse implicit TLS (recommended).

Example request

POST /v1/validate-credentials HTTP/1.1
Host: test.api.migrata.systems
X-Api-Key: mm_live_…
Content-Type: application/json

{
  "source": {
	"server": "imap.gmail.com",
	"port": 993,
	"username": "alice@example.com",
	"password": "app-password-xxxx",
	"useSsl": true
  },
  "destination": {
	"server": "outlook.office365.com",
	"port": 993,
	"username": "alice@contoso.com",
	"password": "s3cret",
	"useSsl": true
  }
}

Example response (200 OK)

{
  "source": {
	"verified": true,
	"server": "imap.gmail.com",
	"port": 993,
	"useSsl": true,
	"providerName": "Gmail",
	"failureReason": null,
	"message": "Login succeeded."
  },
  "destination": {
	"verified": false,
	"server": "outlook.office365.com",
	"port": 993,
	"useSsl": true,
	"providerName": "Microsoft 365",
	"failureReason": "auth_failed",
	"message": "Authentication failed. Check the username and password."
  }
}

Failure reasons

CodeMeaning
auth_failedServer reachable; username/password rejected.
host_unreachableCould not establish a TCP connection.
tls_errorTLS handshake failed (certificate or protocol).
timeoutConnection or login timed out.
unknown_hostDNS lookup failed for the supplied server.
invalid_emailSupplied username is not a valid address and autoconfig was needed.
internal_errorUnexpected server-side error.

POST/v1

Scope: migrations:create

Creates and queues a single mailbox migration. Returns 201 Created with the new migration's status object, including a stable id that you can poll or expect in webhook events.

Request body

FieldTypeNotes
namestringRequired. Human-readable label.
sourceMailboxEndpointRequired.
destinationMailboxEndpointRequired.
foldersstring[]Optional. If empty, all folders are migrated.
fromDateISO-8601 datetimeOptional date-range filter (inclusive).
toDateISO-8601 datetimeOptional date-range filter (inclusive). Must be ≥ fromDate.
startAtISO-8601 datetimeOptional. UTC time when the copy may begin. Omit it to queue the migration immediately. A value with an offset is converted to UTC. Digits with no offset are already UTC. A time that is not in the future is rejected.

Example request

POST /v1 HTTP/1.1
Host: test.api.migrata.systems
X-Api-Key: mm_live_…
Content-Type: application/json

{
  "name": "Alice → Contoso",
  "source": {
	"server": "imap.gmail.com", "port": 993, "useSsl": true,
	"username": "alice@example.com", "password": "app-password-xxxx"
  },
  "destination": {
	"server": "outlook.office365.com", "port": 993, "useSsl": true,
	"username": "alice@contoso.com", "password": "s3cret"
  },
  "folders": ["INBOX", "Sent", "Archive"],
  "fromDate": "2023-01-01T00:00:00Z"
}

Example response (201 Created)

{
  "id": "mig_8f3c1d2b5a",
  "name": "Alice → Contoso",
  "status": "Scheduled",
  "statusMessage": null,
  "totalMessages": 0,
  "messagesCopied": 0,
  "totalSizeBytes": 0,
  "sizeBytesCopied": null,
  "createdAt": "2025-01-15T12:04:08Z",
  "startAt": null,
  "startedAt": null,
  "completedAt": null,
  "error": null
}

GET/v1/{id}

Scope: migrations:read

Returns the current status of a single migration.

Path parameters

NameTypeNotes
idstringThe migration id returned by POST /v1.

Response fields

FieldTypeNotes
idstringPublic migration id.
namestringThe label you supplied.
statusstringOne of Scheduled, Running, Completed, Failed, Cancelled.
statusMessagestring?Optional context for the current status.
totalMessagesintTotal messages discovered to migrate.
messagesCopiedintMessages copied so far.
totalSizeBytesnumberTotal size to migrate, in bytes.
sizeBytesCopiednumber?Size copied so far, in bytes.
createdAtdatetimeUTC.
startAtdatetime?UTC time the copy may begin. Null when the migration was not scheduled. This is not the moment the worker started.
startedAtdatetime?Set when the worker begins.
completedAtdatetime?Set on terminal status.
errorstring?Failure reason on Failed.

GET/v1/bulk-migrations/{id}

Scope: migrations:read

Returns a bulk migration summary including all child jobs.

Example response (200 OK)

{
  "id": "bulk_2a91…",
  "label": "Acme tenant cutover",
  "status": "Running",
  "totalJobs": 25,
  "completedJobs": 9,
  "failedJobs": 1,
  "totalSizeBytes": 187234567890,
  "totalCost": 49.50,
  "currency": "USD",
  "createdAt": "2025-01-15T11:00:00Z",
  "jobs": [
	{ "id": "mig_…", "name": "user1@acme.com", "status": "Completed", "...": "..." }
  ]
}

Webhooks — Overview

Instead of polling, you can receive HTTP POST callbacks to a URL of your choice whenever a migration or bulk migration changes state. Each API key is associated with at most one webhook URL.

Configuration

Webhook destination is stored alongside your API key. It is configured by setting two fields on the key record:

FieldTypeNotes
clientWebhookUrlstringHTTPS URL that will receive events. http:// is rejected in production.
clientWebhookApiKeystring?Optional shared secret. When set, MailMigrata sends it in the X-MailMigrata-Client-Key header so your endpoint can authenticate the caller. Also used to compute the signature in X-MailMigrata-Signature.
Set these via the dashboard or your account API. A single key may emit events for many migrations; all of them are delivered to the same URL.

Event Types

EventWhen
migration.scheduledA migration was created and queued.
migration.startedThe worker began processing the migration.
migration.progressPeriodic progress update (throttled; not every message).
migration.completedMigration finished successfully.
migration.failedMigration failed terminally.
bulk.progressA bulk migration aggregate counter changed.
bulk.completedAll child jobs reached a terminal state.

Payload & Headers

Headers sent on every delivery

HeaderNotes
Content-Type: application/jsonBody is UTF-8 JSON.
User-Agent: MailMigrata-Webhook/1.0Identifies the sender.
X-MailMigrata-EventEvent type, e.g. migration.completed.
X-MailMigrata-DeliveryUnique delivery id. Use to de-duplicate retries.
X-MailMigrata-TimestampUnix seconds (UTC) when the payload was signed.
X-MailMigrata-Signaturesha256=… HMAC of {timestamp}.{body}. See below.
X-MailMigrata-Client-KeyEchoes clientWebhookApiKey if you set one. Useful for trivial auth.

Example payload — migration.progress

{
  "event": "migration.progress",
  "deliveryId": "evt_01J6Z9K…",
  "occurredAt": "2025-01-15T12:34:56Z",
  "data": {
	"id": "mig_8f3c1d2b5a",
	"name": "Alice → Contoso",
	"status": "Running",
	"totalMessages": 12450,
	"messagesCopied": 3120,
	"totalSizeBytes": 9876543210,
	"sizeBytesCopied": 2517394621,
	"createdAt": "2025-01-15T12:04:08Z",
	"startedAt": "2025-01-15T12:05:11Z",
	"completedAt": null,
	"error": null
  }
}

Example payload — migration.failed

{
  "event": "migration.failed",
  "deliveryId": "evt_01J6ZA2…",
  "occurredAt": "2025-01-15T13:01:22Z",
  "data": {
	"id": "mig_8f3c1d2b5a",
	"name": "Alice → Contoso",
	"status": "Failed",
	"error": "Source authentication failed after 3 attempts."
  }
}

Signature Verification

If you configured clientWebhookApiKey, MailMigrata signs every payload so you can confirm it came from us and was not modified.

  1. Read X-MailMigrata-Timestamp (Unix seconds) and the raw request body.
  2. Reject if the timestamp is more than 5 minutes from your server clock (protects against replays).
  3. Compute HMAC_SHA256(secret = clientWebhookApiKey, message = "{timestamp}.{body}") and hex-encode.
  4. Compare to the value after sha256= in X-MailMigrata-Signature using a constant-time comparison.

Node.js verification

import crypto from "node:crypto";

export function verifyMailMigrataSignature(req, secret) {
  const ts  = req.header("X-MailMigrata-Timestamp");
  const sig = req.header("X-MailMigrata-Signature") || "";
  const raw = req.rawBody; // Buffer — capture before JSON parsing
  if (!ts || !raw) return false;
  if (Math.abs(Date.now()/1000 - Number(ts)) > 300) return false;

  const expected = "sha256=" + crypto
	.createHmac("sha256", secret)
	.update(`${ts}.`).update(raw)
	.digest("hex");

  const a = Buffer.from(sig);
  const b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

C# verification

using System.Security.Cryptography;
using System.Text;

public static bool VerifyMailMigrataSignature(
	string timestamp, string signatureHeader, byte[] body, string secret)
{
	if (!long.TryParse(timestamp, out var ts)) return false;
	var skew = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts;
	if (Math.Abs(skew) > 300) return false;

	using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
	hmac.TransformBlock(Encoding.UTF8.GetBytes(timestamp + "."), 0,
		timestamp.Length + 1, null, 0);
	hmac.TransformFinalBlock(body, 0, body.Length);
	var expected = "sha256=" + Convert.ToHexString(hmac.Hash!).ToLowerInvariant();

	return CryptographicOperations.FixedTimeEquals(
		Encoding.ASCII.GetBytes(expected),
		Encoding.ASCII.GetBytes(signatureHeader ?? ""));
}

Retry Policy


Quickstart — cURL

# 1. Validate credentials
curl -sS https://test.api.migrata.systems/v1/validate-credentials \
  -H "X-Api-Key: $MM_KEY" \
  -H "Content-Type: application/json" \
  -d '{
	"source":      {"server":"imap.gmail.com","username":"alice@example.com","password":"app-pwd"},
	"destination": {"server":"outlook.office365.com","username":"alice@contoso.com","password":"s3cret"}
  }'

# 2. Create migration
curl -sS https://test.api.migrata.systems/v1 \
  -H "X-Api-Key: $MM_KEY" \
  -H "Content-Type: application/json" \
  -d '{
	"name":"Alice → Contoso",
	"source":      {"server":"imap.gmail.com","username":"alice@example.com","password":"app-pwd"},
	"destination": {"server":"outlook.office365.com","username":"alice@contoso.com","password":"s3cret"}
  }'

# 3. Poll status (or rely on webhooks)
curl -sS https://test.api.migrata.systems/v1/mig_8f3c1d2b5a \
  -H "X-Api-Key: $MM_KEY"

Node.js

import fetch from "node-fetch";

const BASE = "https://test.api.migrata.systems";
const KEY  = process.env.MM_KEY;

async function mm(path, init = {}) {
  const res = await fetch(`${BASE}${path}`, {
	...init,
	headers: { "X-Api-Key": KEY, "Content-Type": "application/json", ...(init.headers||{}) },
  });
  if (!res.ok) throw Object.assign(new Error(`MM ${res.status}`), { body: await res.json().catch(()=>null) });
  return res.json();
}

const job = await mm("/v1", {
  method: "POST",
  body: JSON.stringify({
	name: "Alice → Contoso",
	source:      { server:"imap.gmail.com",        username:"alice@example.com", password:"app-pwd" },
	destination: { server:"outlook.office365.com", username:"alice@contoso.com", password:"s3cret"  },
  }),
});
console.log("Migration id:", job.id);

C#

using System.Net.Http.Json;

var http = new HttpClient { BaseAddress = new Uri("https://test.api.migrata.systems") };
http.DefaultRequestHeaders.Add("X-Api-Key", Environment.GetEnvironmentVariable("MM_KEY"));

var resp = await http.PostAsJsonAsync("/v1", new {
	name = "Alice \u2192 Contoso",
	source      = new { server="imap.gmail.com",        username="alice@example.com", password="app-pwd" },
	destination = new { server="outlook.office365.com", username="alice@contoso.com", password="s3cret"  }
});
resp.EnsureSuccessStatusCode();
var status = await resp.Content.ReadFromJsonAsync<Dictionary<string,object>>();
Console.WriteLine($"Migration id: {status!["id"]}");

Python

import os, requests

BASE = "https://test.api.migrata.systems"
H = {"X-Api-Key": os.environ["MM_KEY"], "Content-Type": "application/json"}

r = requests.post(f"{BASE}/v1", headers=H, json={
	"name": "Alice → Contoso",
	"source":      {"server":"imap.gmail.com","username":"alice@example.com","password":"app-pwd"},
	"destination": {"server":"outlook.office365.com","username":"alice@contoso.com","password":"s3cret"},
})
r.raise_for_status()
print("Migration id:", r.json()["id"])

mailmigrata.com