✉ MailCraft API Reference

Getting started

Introduction

The MailCraft REST API lets you manage contacts, lists, templates and send transactional, bulk and campaign email from your own code.

These docs are written against the live API. Where the live behaviour differs from the official reference, the live behaviour is documented. Every page carries a status badge: ✅ Verified live · 🟡 Partly verified · ⚠️ Not yet verified (request from the official docs; no response example) · 🔒 Dashboard session only (an API key is refused)

Base URL

text
https://<your-mailcraft-domain>/api/v1

Examples use https://mailcraft.example.com/api/v1.

Authentication

Send your API key as a Bearer token on every request:

http
Authorization: Bearer mc_live_xxx

Create a key in the dashboard under Organization Settings → API Keys. It is shown once. Keep it in an environment variable (MAILCRAFT_API_KEY) — never commit it. A missing, unknown or revoked key returns 401 (often with an empty body).

Dashboard-only endpoints

Some routes refuse API keys even though they are listed in the reference:

EndpointAPI key result
POST/PUT/PATCH/DELETE /templates…, …/publish, …/duplicate403 Forbidden
GET /tags, POST /tags401 Unauthenticated
GET /contacts/{id}/recommendations401 (test key)
GET /logs403 (test key)

These work only with a logged-in dashboard session (mc_session cookie + X-CSRF-TOKEN), which is not meant for integrations. Segments, preference topics, the suppression list, providers and org settings are dashboard-only by design.

Responses

Errors

Most errors use this envelope with a matching 4xx/5xx status. Codes are PascalCase:

json
{ "error": { "code": "NotFound", "message": "Contact not found." } }

Seen codes: ValidationFailed, NotFound, Conflict, Unauthenticated, Forbidden, Unexpected (500).

Other shapes you must handle:

ShapeWhen
ASP.NET ProblemDetails { "type", "title", "status": 400, "errors": { "field": ["msg"] }, "traceId" }Model-binding errors: bad GUID, limit=abc, wrong JSON type (e.g. a number where a string is expected)
Title-only ProblemDetails { "title": "Not Found", "status": 404 }Unknown /lists/{id}
Empty bodyNon-GUID ids (404), missing/bad key (401)
HTML 413 from the gatewayRequest body over 1 MiB

The helpers below normalise all of these into one exception with status, code and message.

Pagination

Paging is not uniform — check each endpoint:

EndpointBehaviour
GET /contacts, GET /transactional?limit=N&cursor=<nextCursor> → { "items": [...], "nextCursor": "…" | null }. after/before are ignored. On /contacts, omitting limit returns everything; /transactional defaults to 50 (max 200).
GET /lists, /templates, /org/contact-properties, /contacts/importBare array, not paged — everything is returned.
GET /inboundBare array, limit only (default 20). Older messages cannot be reached.
GET /logs, /broadcasts/{id}/recipientsDocs say limit/after → { data, hasMore } — not verified.

Limits

LimitValue
Request body (gateway)1 MiB → HTML 413. With Base64 that is ≈700 KB of attachment.
Attachments per send10 (documented 10 MB each, unreachable behind the gateway)
Batch send100 items
Bulk send recipients / JSON import rows1000
Template variables50
Share link / attachment URL lifetime≤48 h / ≈1 h (each call rotates the URL)

No rate-limit headers have been observed.

Webhook signatures

Deliveries carry X-Mailchimp-Clone-Event and X-Mailchimp-Clone-Signature = Base64(HMAC-SHA256(raw body, signingSecret)).

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

static bool IsValid(byte[] rawBody, string signatureHeader, string signingSecret)
{
    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(signingSecret));
    var expected = Convert.ToBase64String(hmac.ComputeHash(rawBody));
    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(signatureHeader));
}
python
import base64, hashlib, hmac

def is_valid(raw_body: bytes, signature_header: str, signing_secret: str) -> bool:
    expected = base64.b64encode(
        hmac.new(signing_secret.encode(), raw_body, hashlib.sha256).digest()).decode()
    return hmac.compare_digest(expected, signature_header)

Helpers

Every endpoint page uses one small helper per language. Copy it once into your project. It is plain REST — no SDK package.

.NET (C#) — MailCraftApi.cs

Requires .NET 8+ (uses only System.Net.Http and System.Text.Json).

csharp
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

/// <summary>Minimal MailCraft REST helper (HttpClient + System.Text.Json).</summary>
public sealed class MailCraftApi : IDisposable
{
    public static readonly JsonSerializerOptions Pretty = new() { WriteIndented = true };
    private readonly HttpClient _http;

    public MailCraftApi(string apiKey, string baseUrl = "https://mailcraft.example.com/api/v1")
    {
        _http = new HttpClient { BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/") };
        _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    /// <summary>Sends a request; returns the parsed JSON, or null for 204/empty bodies.</summary>
    public async Task<JsonNode?> SendAsync(HttpMethod method, string path, JsonNode? body = null,
        CancellationToken ct = default)
    {
        using var req = new HttpRequestMessage(method, path.TrimStart('/'));
        if (body is not null)
            req.Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
        using var res = await _http.SendAsync(req, ct);
        var text = await res.Content.ReadAsStringAsync(ct);
        if (!res.IsSuccessStatusCode) throw MailCraftException.From(res.StatusCode, text);
        return string.IsNullOrWhiteSpace(text) ? null : JsonNode.Parse(text);
    }

    /// <summary>Downloads raw bytes (e.g. inbound attachments).</summary>
    public async Task<byte[]> GetBytesAsync(string path, CancellationToken ct = default)
    {
        using var res = await _http.GetAsync(path.TrimStart('/'), ct);
        if (!res.IsSuccessStatusCode)
            throw MailCraftException.From(res.StatusCode, await res.Content.ReadAsStringAsync(ct));
        return await res.Content.ReadAsByteArrayAsync(ct);
    }

    /// <summary>Iterates a cursor-paged list ({ items, nextCursor }), e.g. /contacts, /transactional.</summary>
    public async IAsyncEnumerable<JsonNode> PaginateAsync(string path, int limit = 100,
        [EnumeratorCancellation] CancellationToken ct = default)
    {
        string? cursor = null;
        do
        {
            var sep = path.Contains('?') ? '&' : '?';
            var url = $"{path}{sep}limit={limit}" + (cursor is null ? "" : $"&cursor={Uri.EscapeDataString(cursor)}");
            var page = await SendAsync(HttpMethod.Get, url, null, ct);
            foreach (var item in page?["items"]?.AsArray() ?? new JsonArray())
                if (item is not null) yield return item;
            cursor = page?["nextCursor"]?.GetValue<string>();
        } while (cursor is not null);
    }

    public void Dispose() => _http.Dispose();
}

public sealed class MailCraftException : Exception
{
    public HttpStatusCode Status { get; }
    public string Code { get; }
    public string? RawBody { get; }

    private MailCraftException(HttpStatusCode status, string code, string message, string? raw)
        : base($"{(int)status} {code}: {message}") { Status = status; Code = code; RawBody = raw; }

    public static MailCraftException From(HttpStatusCode status, string text)
    {
        var fallback = $"http_{(int)status}";
        if (string.IsNullOrWhiteSpace(text)) return new(status, fallback, status.ToString(), null);
        try
        {
            var node = JsonNode.Parse(text);
            if (node?["error"] is JsonObject e) // { "error": { "code", "message" } }
                return new(status, e["code"]?.ToString() ?? fallback, e["message"]?.ToString() ?? "", text);
            if (node?["title"] is not null) // ASP.NET ProblemDetails
            {
                if (node["errors"] is JsonObject errs && errs.Count > 0)
                {
                    var msg = string.Join("; ", errs.Select(kv => $"{kv.Key}: {string.Join(" ", kv.Value!.AsArray())}"));
                    return new(status, "ValidationFailed", msg, text);
                }
                return new(status, fallback, node["title"]!.ToString(), text);
            }
        }
        catch (JsonException) { /* HTML 413 from the gateway, etc. */ }
        return new(status, fallback, text.Length > 200 ? text[..200] : text, text);
    }
}

Usage:

csharp
using var mc = new MailCraftApi(Environment.GetEnvironmentVariable("MAILCRAFT_API_KEY")!);
try
{
    await foreach (var contact in mc.PaginateAsync("/contacts"))
        Console.WriteLine(contact["email"]);
}
catch (MailCraftException ex)
{
    Console.WriteLine($"{ex.Status} {ex.Code}: {ex.Message}");
}

Python — mailcraft.py

Requires pip install requests.

python
"""Minimal MailCraft REST helper (requests). Save as mailcraft.py."""
import requests


class MailCraftError(Exception):
    def __init__(self, status, code, message, body=None):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code, self.message, self.body = status, code, message, body


class MailCraft:
    def __init__(self, api_key, base_url="https://mailcraft.example.com/api/v1", timeout=30):
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Accept": "application/json",
        })

    def request(self, method, path, *, json=None, params=None, raw=False):
        resp = self.session.request(method, self.base_url + path, json=json,
                                    params=params, timeout=self.timeout)
        if resp.status_code >= 400:
            raise self._error(resp)
        if raw:
            return resp.content
        if resp.status_code == 204 or not resp.content:
            return None
        return resp.json()

    def paginate(self, path, limit=100, **params):
        """Yield every item from a cursor-paged list ({items, nextCursor})."""
        cursor = None
        while True:
            q = dict(params, limit=limit)
            if cursor:
                q["cursor"] = cursor
            page = self.request("GET", path, params=q)
            yield from page["items"]
            cursor = page.get("nextCursor")
            if not cursor:
                return

    @staticmethod
    def _error(resp):
        try:
            body = resp.json()
        except ValueError:
            # empty body (some 401/404s) or the gateway's HTML 413
            return MailCraftError(resp.status_code, f"http_{resp.status_code}",
                                  resp.reason or "HTTP error", resp.text or None)
        if isinstance(body, dict) and isinstance(body.get("error"), dict):
            e = body["error"]
            return MailCraftError(resp.status_code, e.get("code"), e.get("message"), body)
        if isinstance(body, dict) and "title" in body:  # ASP.NET ProblemDetails
            errs = body.get("errors") or {}
            msg = "; ".join(f"{k}: {' '.join(v)}" for k, v in errs.items()) or body["title"]
            code = "ValidationFailed" if errs else f"http_{resp.status_code}"
            return MailCraftError(resp.status_code, code, msg, body)
        return MailCraftError(resp.status_code, f"http_{resp.status_code}", str(body), body)

Usage:

python
import os
from mailcraft import MailCraft, MailCraftError

mc = MailCraft(os.environ["MAILCRAFT_API_KEY"])
try:
    for contact in mc.paginate("/contacts"):
        print(contact["email"])
except MailCraftError as e:
    print(e.status, e.code, e.message)

All endpoints

Contacts

GETList contacts/contactsVerified
POSTCreate contact/contactsVerified
GETRetrieve contact/contacts/{id|email}Verified
PUTReplace contact/contacts/{id}Verified
PATCHUpdate contact/contacts/{id|email}Verified
DELETEDelete contact/contacts/{id|email}Verified
POSTAdd contact to list/contacts/{id|email}/lists/{listId}Verified
GETList contact's lists/contacts/{id|email}/listsVerified
DELETERemove contact from list/contacts/{id|email}/lists/{listId}Verified
GETGet topic subscriptions/contacts/{id|email}/topicsVerified
PATCHUpdate topic subscriptions/contacts/{id|email}/topicsVerified
POSTImport contacts (JSON)/contacts/import-jsonVerified
GETRetrieve import job/contacts/import/{jobId}Verified
GETList import jobs/contacts/importVerified
GETGet contact timeline/contacts/{id}/timelinePartly verified
GETGet recommendations/contacts/{id}/recommendationsNot verified

Lists

GETList lists/listsVerified
POSTCreate list/listsVerified
GETRetrieve list/lists/{id}Verified
PUTReplace list/lists/{id}Verified
DELETEDelete list/lists/{id}Verified

Tags

GETList tags/tagsSession only
POSTCreate tag/tagsSession only

Contact properties

GETList contact properties/org/contact-propertiesVerified
POSTCreate contact property/org/contact-propertiesVerified
GETRetrieve contact property/org/contact-properties/{id}Verified
PATCHUpdate contact property/org/contact-properties/{id}Verified
DELETEDelete contact property/org/contact-properties/{id}Verified

Templates

GETList templates/templatesVerified
GETRetrieve template/templates/{id|alias}Verified
POSTCreate template/templatesSession only
PUTReplace template/templates/{id|alias}Session only · not verified
PATCHUpdate template/templates/{id|alias}Session only
DELETEDelete template/templates/{id|alias}Session only
POSTPublish template/templates/{id|alias}/publishSession only
POSTDuplicate template/templates/{id|alias}/duplicateSession only

Campaigns

GETList campaigns/campaignsNot verified
POSTCreate campaign/campaignsNot verified
GETRetrieve campaign/campaigns/{id}Not verified
PUTReplace campaign/campaigns/{id}Not verified
DELETEDelete campaign/campaigns/{id}Not verified
POSTSchedule campaign/campaigns/{id}/scheduleNot verified
POSTSend campaign now/campaigns/{id}/send-nowNot verified
POSTCancel campaign/campaigns/{id}/cancelNot verified
GETGet campaign report/campaigns/{id}/reportNot verified

Broadcasts

GETList broadcasts/broadcastsNot verified
POSTCreate broadcast/broadcastsNot verified
GETRetrieve broadcast/broadcasts/{id}Not verified
PATCHUpdate broadcast/broadcasts/{id}Not verified
POSTSend broadcast/broadcasts/{id}/sendNot verified
POSTCancel broadcast/broadcasts/{id}/cancelNot verified
DELETEDelete broadcast/broadcasts/{id}Not verified
POSTDuplicate broadcast/broadcasts/{id}/duplicateNot verified
GETList broadcast recipients/broadcasts/{id}/recipientsNot verified
GETList clicked links/broadcasts/{id}/clicked-linksNot verified

Automations

GETList automations/automationsNot verified
POSTCreate automation/automationsNot verified
GETRetrieve automation/automations/{id}Not verified
PUTReplace automation graph/automations/{id}Not verified
PATCHUpdate automation/automations/{id}Not verified
DELETEDelete automation/automations/{id}Not verified
POSTDuplicate automation/automations/{id}/duplicateNot verified
POSTActivate automation/automations/{id}/activateNot verified
POSTPause automation/automations/{id}/pauseNot verified
GETList runs/automations/{id}/runsNot verified
GETRetrieve run/automations/{id}/runs/{runId}Not verified
POSTTrigger automation/automations/{id}/triggerNot verified

Custom events

POSTCreate event definition/eventsNot verified
GETList event definitions/eventsNot verified
GETRetrieve event definition/events/{id}Not verified

Transactional

POSTSend email/transactional/sendVerified
POSTSend with attachments/transactional/sendVerified
POSTSend batch/transactional/send/batchVerified
GETList sends/transactionalVerified
GETRetrieve send/transactional/{sendId}Verified
PATCHReschedule send/transactional/{sendId}Verified
POSTCancel send/transactional/{sendId}/cancelVerified
POSTShare send/transactional/{sendId}/shareVerified
GETList send attachments/transactional/{sendId}/attachmentsVerified
GETRetrieve send attachment/transactional/{sendId}/attachments/{attachmentId}Verified

Bulk

POSTSend bulk email/bulk/sendNot verified

Inbound

GETList inbound emails/inboundVerified
GETRetrieve inbound email/inbound/{id}Verified
GETList inbound attachments/inbound/{id}/attachmentsVerified
GETDownload inbound attachment/inbound/{id}/attachments/{attachmentId}Verified
POSTReply to inbound email/inbound/{id}/replyNot verified

Webhooks

GETList webhook subscriptions/org/webhook-subscriptionsNot verified
GETRetrieve webhook subscription/org/webhook-subscriptions/{id}Not verified
POSTCreate webhook subscription/org/webhook-subscriptionsNot verified
PATCHUpdate webhook subscription/org/webhook-subscriptions/{id}Not verified
DELETEDelete webhook subscription/org/webhook-subscriptions/{id}Not verified

Analytics

GETGet metrics/analytics/metricsNot verified

API request logs

GETList API request logs/logsNot verified
GETRetrieve API request log/logs/{id}Not verified