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
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:
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:
| Endpoint | API key result |
|---|---|
POST/PUT/PATCH/DELETE /templates…, …/publish, …/duplicate | 403 Forbidden |
GET /tags, POST /tags | 401 Unauthenticated |
GET /contacts/{id}/recommendations | 401 (test key) |
GET /logs | 403 (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
- Success is usually 200 (also for creates — not 201). Deletes and some actions return 204 with no body.
POST /transactional/sendand/send/batchreturn 202.- Field names are camelCase. Timestamps are ISO-8601 UTC.
- Enums are sometimes integers in responses but strings in requests (e.g. contact property
type: send"number", receive1).
Errors
Most errors use this envelope with a matching 4xx/5xx status. Codes are PascalCase:
{ "error": { "code": "NotFound", "message": "Contact not found." } }
Seen codes: ValidationFailed, NotFound, Conflict, Unauthenticated, Forbidden, Unexpected (500).
Other shapes you must handle:
| Shape | When |
|---|---|
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 body | Non-GUID ids (404), missing/bad key (401) |
| HTML 413 from the gateway | Request 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:
| Endpoint | Behaviour |
|---|---|
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/import | Bare array, not paged — everything is returned. |
GET /inbound | Bare array, limit only (default 20). Older messages cannot be reached. |
GET /logs, /broadcasts/{id}/recipients | Docs say limit/after → { data, hasMore } — not verified. |
Limits
| Limit | Value |
|---|---|
| Request body (gateway) | 1 MiB → HTML 413. With Base64 that is ≈700 KB of attachment. |
| Attachments per send | 10 (documented 10 MB each, unreachable behind the gateway) |
| Batch send | 100 items |
| Bulk send recipients / JSON import rows | 1000 |
| Template variables | 50 |
| 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)).
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));
}
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).
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:
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.
"""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:
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
| GET | List contacts | /contacts | Verified |
| POST | Create contact | /contacts | Verified |
| GET | Retrieve contact | /contacts/{id|email} | Verified |
| PUT | Replace contact | /contacts/{id} | Verified |
| PATCH | Update contact | /contacts/{id|email} | Verified |
| DELETE | Delete contact | /contacts/{id|email} | Verified |
| POST | Add contact to list | /contacts/{id|email}/lists/{listId} | Verified |
| GET | List contact's lists | /contacts/{id|email}/lists | Verified |
| DELETE | Remove contact from list | /contacts/{id|email}/lists/{listId} | Verified |
| GET | Get topic subscriptions | /contacts/{id|email}/topics | Verified |
| PATCH | Update topic subscriptions | /contacts/{id|email}/topics | Verified |
| POST | Import contacts (JSON) | /contacts/import-json | Verified |
| GET | Retrieve import job | /contacts/import/{jobId} | Verified |
| GET | List import jobs | /contacts/import | Verified |
| GET | Get contact timeline | /contacts/{id}/timeline | Partly verified |
| GET | Get recommendations | /contacts/{id}/recommendations | Not verified |
Lists
| GET | List lists | /lists | Verified |
| POST | Create list | /lists | Verified |
| GET | Retrieve list | /lists/{id} | Verified |
| PUT | Replace list | /lists/{id} | Verified |
| DELETE | Delete list | /lists/{id} | Verified |
Tags
| GET | List tags | /tags | Session only |
| POST | Create tag | /tags | Session only |
Contact properties
| GET | List contact properties | /org/contact-properties | Verified |
| POST | Create contact property | /org/contact-properties | Verified |
| GET | Retrieve contact property | /org/contact-properties/{id} | Verified |
| PATCH | Update contact property | /org/contact-properties/{id} | Verified |
| DELETE | Delete contact property | /org/contact-properties/{id} | Verified |
Templates
| GET | List templates | /templates | Verified |
| GET | Retrieve template | /templates/{id|alias} | Verified |
| POST | Create template | /templates | Session only |
| PUT | Replace template | /templates/{id|alias} | Session only · not verified |
| PATCH | Update template | /templates/{id|alias} | Session only |
| DELETE | Delete template | /templates/{id|alias} | Session only |
| POST | Publish template | /templates/{id|alias}/publish | Session only |
| POST | Duplicate template | /templates/{id|alias}/duplicate | Session only |
Campaigns
| GET | List campaigns | /campaigns | Not verified |
| POST | Create campaign | /campaigns | Not verified |
| GET | Retrieve campaign | /campaigns/{id} | Not verified |
| PUT | Replace campaign | /campaigns/{id} | Not verified |
| DELETE | Delete campaign | /campaigns/{id} | Not verified |
| POST | Schedule campaign | /campaigns/{id}/schedule | Not verified |
| POST | Send campaign now | /campaigns/{id}/send-now | Not verified |
| POST | Cancel campaign | /campaigns/{id}/cancel | Not verified |
| GET | Get campaign report | /campaigns/{id}/report | Not verified |
Broadcasts
| GET | List broadcasts | /broadcasts | Not verified |
| POST | Create broadcast | /broadcasts | Not verified |
| GET | Retrieve broadcast | /broadcasts/{id} | Not verified |
| PATCH | Update broadcast | /broadcasts/{id} | Not verified |
| POST | Send broadcast | /broadcasts/{id}/send | Not verified |
| POST | Cancel broadcast | /broadcasts/{id}/cancel | Not verified |
| DELETE | Delete broadcast | /broadcasts/{id} | Not verified |
| POST | Duplicate broadcast | /broadcasts/{id}/duplicate | Not verified |
| GET | List broadcast recipients | /broadcasts/{id}/recipients | Not verified |
| GET | List clicked links | /broadcasts/{id}/clicked-links | Not verified |
Automations
| GET | List automations | /automations | Not verified |
| POST | Create automation | /automations | Not verified |
| GET | Retrieve automation | /automations/{id} | Not verified |
| PUT | Replace automation graph | /automations/{id} | Not verified |
| PATCH | Update automation | /automations/{id} | Not verified |
| DELETE | Delete automation | /automations/{id} | Not verified |
| POST | Duplicate automation | /automations/{id}/duplicate | Not verified |
| POST | Activate automation | /automations/{id}/activate | Not verified |
| POST | Pause automation | /automations/{id}/pause | Not verified |
| GET | List runs | /automations/{id}/runs | Not verified |
| GET | Retrieve run | /automations/{id}/runs/{runId} | Not verified |
| POST | Trigger automation | /automations/{id}/trigger | Not verified |
Custom events
| POST | Create event definition | /events | Not verified |
| GET | List event definitions | /events | Not verified |
| GET | Retrieve event definition | /events/{id} | Not verified |
Transactional
| POST | Send email | /transactional/send | Verified |
| POST | Send with attachments | /transactional/send | Verified |
| POST | Send batch | /transactional/send/batch | Verified |
| GET | List sends | /transactional | Verified |
| GET | Retrieve send | /transactional/{sendId} | Verified |
| PATCH | Reschedule send | /transactional/{sendId} | Verified |
| POST | Cancel send | /transactional/{sendId}/cancel | Verified |
| POST | Share send | /transactional/{sendId}/share | Verified |
| GET | List send attachments | /transactional/{sendId}/attachments | Verified |
| GET | Retrieve send attachment | /transactional/{sendId}/attachments/{attachmentId} | Verified |
Bulk
| POST | Send bulk email | /bulk/send | Not verified |
Inbound
| GET | List inbound emails | /inbound | Verified |
| GET | Retrieve inbound email | /inbound/{id} | Verified |
| GET | List inbound attachments | /inbound/{id}/attachments | Verified |
| GET | Download inbound attachment | /inbound/{id}/attachments/{attachmentId} | Verified |
| POST | Reply to inbound email | /inbound/{id}/reply | Not verified |
Webhooks
| GET | List webhook subscriptions | /org/webhook-subscriptions | Not verified |
| GET | Retrieve webhook subscription | /org/webhook-subscriptions/{id} | Not verified |
| POST | Create webhook subscription | /org/webhook-subscriptions | Not verified |
| PATCH | Update webhook subscription | /org/webhook-subscriptions/{id} | Not verified |
| DELETE | Delete webhook subscription | /org/webhook-subscriptions/{id} | Not verified |
Analytics
| GET | Get metrics | /analytics/metrics | Not verified |
API request logs
| GET | List API request logs | /logs | Not verified |
| GET | Retrieve API request log | /logs/{id} | Not verified |