Documentation
Overview
mail2app gives you an email address. Every message that arrives there is parsed and sent to your application as one HTTP POST with a JSON body, signed with a secret only you hold. Delivery is retried until your endpoint answers; the message is stored encrypted until it has been delivered, then deleted.
Three things to set up:
- An address — you get one at sign-up:
inbox@token.mail2app.com. Paid plans name their own. - A webhook endpoint — the URL your application listens on, and the secret we sign with.
- Forwarding — point your mailbox, your domain or a vendor's "send invoices to" at the address. Or, on Pro and Max, point a domain of your own straight at us.
Then read what a delivery looks like and verify the signature. Everything else is optional.
Your address
Every account has a subdomain of its own: a random 12-character token on the free plan (k7m2p4q9x3rz.mail2app.com), a name of your choosing on Pro and Max (shop.mail2app.com). The local part is inbox on the free plan; paid plans create named addresses (orders@, support@) — one per thing you want to tell apart.
Plus-addressing
Any address accepts a tag after a plus sign: mail to [email protected] reaches orders@, and the payload carries envelope.plus_tag: "acme". Hand a different tag to each sender and you can route without creating addresses.
What is refused at the door
Mail to an address that does not exist is rejected by the mail server (550 5.1.1). Mail to a paused address, or past about twice your daily cap, is told to try later (4xx): the sending server keeps it and retries, nothing is lost. Messages larger than your plan's limit (2 MB on the free plan) are recorded as dropped.
Your own domain
On Pro (1 domain) and Max (5), addresses can live on a domain you control instead of ours: [email protected]. Mail sent there comes straight to us, with no forwarding rule in between, and is delivered like any other inbox's. Add it on the Domains page.
Use a name that only mail2app will receive at, such as inbound.example.com. Pointing a name at us moves all of its mail here, so never use the domain your own mailboxes are on.
Pointing it here
One CNAME record (recommended): inbound.example.com CNAME your-token.mail2app.com, where the target is your account's own subdomain, shown on the Domains page. Our MX records answer through it, and if our mail servers ever change, you change nothing.
MX records and a TXT record, when the name already has other records (a CNAME must be alone) or is the top of your domain: an MX record for each of our mail servers, plus _mail2app.inbound.example.com TXT "mail2app-verify=token". The exact values are on the Domains page. Every MX record on the name must be ours.
Either way, the record names your account, which is how we know the domain is yours: nobody else can verify a domain you control.
Verification
A new domain is Waiting for DNS. We check every few minutes at first (press Check now to look straight away, past any cache) and email you when it is Verified. You can create inboxes on it before then; mail to them is refused until it is verified.
We keep checking. If the records stop pointing at us, the domain shows DNS changed and you are emailed: mail is still accepted for 7 days, in case it is a change in progress. After that it lapses: its mail is refused until the records are back and it is checked again. A check that cannot reach the DNS servers changes nothing.
Over the API: GET /api/m2a/domains, POST /api/m2a/domains with {"kind": "custom", "host": "inbound.example.com", "verify_method": "cname"}, then POST /api/m2a/domains/{id}/check. Each domain carries its dns_state, the records to add and what the last_check found.
A delivery
One message to one endpoint is one delivery. It arrives as a POST with these headers:
| Header | Value |
|---|---|
Content-Type | application/json |
User-Agent | mail2app-webhooks/1 |
Idempotency-Key | The delivery id — the same on every retry. Dedupe on it. |
X-Mail2app-Event | message.received, or webhook.test for a test send |
X-Mail2app-Message-Id | The message's id (one message can go to several endpoints) |
X-Mail2app-Delivery-Id | The delivery's id (one per message × endpoint) |
X-Mail2app-Inbox-Id | The address's id |
X-Mail2app-Attempt | 1 on the first try, then 2, 3, … |
X-Mail2app-Attempt-Id | Unique per attempt; it also appears as attempt.id in the body |
X-Mail2app-Signature | t=1761900000,v1=… — see signatures |
Custom headers you set on the endpoint (an Authorization for your own gateway, say) are sent too. The body is the payload; it is rebuilt from the stored message on every attempt, so a retry is never a stale copy.
Mail for your address is received by more than one of our servers. A sender whose connection to one of them dropped after the message was taken may send it again to another; we drop a duplicate we can see (the same Message-ID to the same address within seven days), but two copies taken within the same second can both reach you, as two deliveries with different ids. Treat message.message_id together with inbox.id as the key for "have I seen this email", and Idempotency-Key as the key for "have I seen this delivery".
Routing rules
Without rules, every message sent to an address goes to every endpoint attached to it. Rules let one address send different mail to different places: "if the subject contains fred, send it to this endpoint; if it is for +test, send it to that one; anything else goes to the usual one".
- Checked from the top. The first rule that matches decides where the message goes, and nothing below it is checked.
- Keep checking: a rule set to keep checking sends its copy (to a log, say) and lets the rules below decide too.
- Discard: a rule can drop what it matches. The message still shows in your list, as discarded by that rule.
- Otherwise is the last line: the endpoints attached to the address, which get what no rule claimed. With none attached, you choose whether unclaimed mail is held (and sent on when a rule or an endpoint would take it, within seven days) or discarded.
- A rule that is switched off is skipped. A rule with no conditions matches every message.
Make them on the address's page, under Routing: Create rule, choose what to match and where it goes, and drag the rules into the order you want. Test a message under the list shows which rule a message would take as you type, without sending anything. Every message in the list says which rule routed it, and each rule counts what it matched today. The mail servers pick up a change within seconds. Rules come with Basic (5 per address), Pro (25) and above; an address can use as many endpoints, across its rules and Otherwise, as your plan allows per address.
What a rule can test
Text comparisons ignore upper and lower case; matches pattern takes a regular expression. Fields that hold several addresses or names (separated by commas) offer contains, does not contain, the pattern tests and is empty.
| Field | Name | Type |
|---|---|---|
| Subject | subject | text |
| From (address) | from | text |
| From (name) | from_name | text |
| Any recipient | recipients | text |
| To | to | text |
| Cc | cc | text |
| Reply-To | reply_to | text |
| Plus tag (+…) | plus_tag | text |
| Envelope sender | envelope_sender | text |
| Body text | body | text |
| List-Id | list_id | text |
| Has attachments | has_attachments | boolean |
| Number of attachments | attachment_count | number |
| Attachment file names | attachment_names | text |
| Attachment types | attachment_types | text |
| Size (KB) | size_kb | number |
| SPF result | spf | enum |
| DKIM result | dkim | enum |
| DMARC result | dmarc | enum |
Forwarded mail. When another mailbox forwards to your mail2app address, the address the sender used ([email protected]) usually survives only in the message's headers, not in the address mail2app received it at. Any recipient covers both: the address we received it at, To, Cc, Delivered-To, X-Original-To, X-Forwarded-To and Envelope-To. Plus tag is only the tag on the mail2app address itself.
Over the API
curl -X POST https://mail2app.com/api/m2a/inboxes/{inbox_id}/rules \
-H "Authorization: Bearer m2a_xxxxxxxx_…" \
-H "Content-Type: application/json" \
-d '{"name": "Test server", "endpoints": ["{webhook_id}"],
"conditions": {"version": "1.0", "root": {"type": "group", "operator": "and", "children": [
{"type": "condition", "field": "recipients", "operator": "contains", "values": [{"source": "literal", "value": "+test"}]}]}}}'| Call | Does |
|---|---|
GET /api/m2a/inboxes/{id}/rules | The rules in order (id, number, name, conditions, summary in words, action, keep_checking, enabled, paused_reason, endpoints, matched_today), otherwise and your plan's limit |
POST /api/m2a/inboxes/{id}/rules | A new rule at the bottom: conditions (a kConditions document; leave it out for "always"), endpoints (endpoint ids), action (deliver or discard), keep_checking, enabled, name |
PATCH /api/m2a/inboxes/{id}/rules/{rule} | Change any of those (PUT works too); DELETE removes the rule |
PUT /api/m2a/inboxes/{id}/rules | {"order": [rule ids…]}: the new order |
PUT /api/m2a/inboxes/{id}/otherwise | {"action": "hold" | "discard"}: what happens to unclaimed mail while no endpoint is attached. The attached endpoints themselves are /api/m2a/inboxes/{id}/webhooks. |
The live message list (/api/m2a/inboxes/{id}/live) gives each message a routing object: the rules that matched (id and name, in order), whether it went on to otherwise, and the outcome (deliver, discard or hold). It is null for mail routed while the address had no rules. The payload your endpoint receives is unchanged.
The payload
Schema version 1. Changes are additive: a new key may appear, an existing one never changes meaning or goes away. Build your parser to ignore keys it does not know.
{
"schema_version": 1,
"event": "message.received",
"sent_at": "2026-10-31T09:14:05Z",
"attempt": {
"n": 1,
"id": "3f1c9a7e-8d2b-4c6e-9a1f-2b7d4e8c0a53"
},
"message_id": "c0a8e1d2-5b4f-4a7c-8e9d-1f2a3b4c5d6e",
"delivery_id": "6d2f4c8e-1a3b-4c5d-8e7f-9a0b1c2d3e4f",
"inbox": {
"id": "9b8a7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d",
"address": "[email protected]",
"label": "Orders"
},
"envelope": {
"sender": "[email protected]",
"recipient": "[email protected]",
"plus_tag": "acme",
"received_at": "2026-10-31T09:14:02.318Z",
"client_ip": "203.0.113.9"
},
"message": {
"message_id": "<[email protected]>",
"from": {
"name": "Acme Supplies",
"email": "[email protected]"
},
"to": [
{
"name": null,
"email": "[email protected]"
}
],
"cc": [],
"reply_to": [
{
"name": "Accounts",
"email": "[email protected]"
}
],
"subject": "Invoice 4471",
"date": "2026-10-31T09:13:58+00:00",
"text": "Please find attached invoice 4471.\n\nAcme Supplies",
"html": "<p>Please find attached invoice 4471.</p><p>Acme Supplies</p>",
"size": 73240,
"headers": {
"received": [
"from mail.acme-supplies.example (…) by mx-1.mail2app.com …"
],
"message-id": [
"<[email protected]>"
],
"subject": [
"Invoice 4471"
],
"x-priority": [
"3"
]
},
"authentication": {
"spf": "pass",
"dkim": "pass",
"dmarc": "pass",
"arc": null,
"source": "authentication-results"
}
},
"attachments": [
{
"filename": "invoice-4471.pdf",
"content_type": "application/pdf",
"size": 48213,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"inline": false,
"content_id": null,
"url": "https://app.mail2app.com/api/mail_attachments/…/file?…",
"url_expires_at": "2026-11-07T09:14:05Z"
},
{
"filename": "logo.png",
"content_type": "image/png",
"size": 2310,
"sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
"inline": true,
"content_id": "<logo@acme>",
"content_base64": "iVBORw0KGgo…"
}
],
"truncated": {
"text": false,
"html": false
}
}| Key | Meaning |
|---|---|
event | message.received; webhook.test for a test send (then envelope, message_id and delivery_id are null). |
attempt | n counts from 1; id is unique per attempt and matches X-Mail2app-Attempt-Id. |
envelope | What the sending server said at the door: the return path (sender, null for a bounce), the recipient as addressed, the plus_tag, when we received it, the sender's IP. |
message.from / to / cc / reply_to | Parsed addresses: {name, email}; from is one object, the others lists. |
message.text / html | The decoded bodies, UTF-8. Each is cut at 1 MB and truncated.text / truncated.html say so. html is left out when the endpoint has HTML switched off. Treat html as untrusted: sanitise before rendering. |
message.headers | Every header, lower-cased name → list of values in wire order, encoded words decoded. Repeated headers (received) keep every value. |
message.authentication | The SPF / DKIM / DMARC / ARC verdicts the receiving server recorded (pass, fail, none, …); null when there were none. They are what the server found, parsed from Authentication-Results, not re-verified by us. |
attachments | See attachments. inline marks a part referenced from the HTML (a signature logo); content_id is what the HTML refers to it by. |
raw_base64 | The whole message as received, base64 — only when the endpoint asks for it and the plan allows it. |
The whole body is kept under 10 MB: when it would be larger, the largest inline attachment becomes a link (or is omitted) until it fits.
Attachments
Each address (and each endpoint, overriding the address) has an attachment mode:
| Mode | Small attachments | Large attachments |
|---|---|---|
inline | content_base64 in the payload, up to the inline limit | omitted (omitted_reason: too_large) |
url | a signed, time-limited url (and url_expires_at); nothing inline | |
both | inline | a signed url |
none | metadata only (omitted_reason: disabled) | |
The inline limit and how long a link lives are yours to set, within the plan: on the free plan inline up to 256 KB and no links; on Pro inline up to 5 MB and links for up to 7 days. A link is fetched with a plain GET, no authentication: the URL is the credential, so treat it as one. The file's sha256 is in the payload — check it after download.
Attachments travel as links only when we have a copy to serve: a message whose endpoints all use inline is never stored beyond delivery. With links, the file is kept until the last link expires.
Verifying signatures
Every delivery carries
X-Mail2app-Signature: t=1761900000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdwhere t is the Unix time the request was signed and v1 is hex(HMAC-SHA256(secret, t + "." + rawBody)) over the exact bytes of the body. To verify:
- Read the raw request body — the bytes, before any JSON parsing or re-encoding.
- Split the header on commas: take
tand everyv1. - Refuse when
tis more than 300 seconds from your clock (replay protection). - Compute the HMAC with your secret over
t, a dot, and the body; compare it to eachv1with a constant-time comparison. Any match is good.
Two v1 values appear for 24 hours after you rotate a secret: one for the old secret, one for the new. During that window keep both secrets on your side and accept either. Your secret is shown once when the endpoint is created or rotated; it starts with whsec_.
The function on its own, in five languages; a complete receiver puts it to work.
import crypto from 'node:crypto';
// rawBody: the request body BYTES as received — never a re-serialised object.
export function verify(rawBody, header, secrets, toleranceSeconds = 300) {
const t = Number((header.match(/(?:^|,)t=(\d+)/) || [])[1]);
const sigs = [...header.matchAll(/v1=([0-9a-f]+)/g)].map((m) => m[1]);
if (!t || !sigs.length || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
return secrets.some((secret) => {
const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex');
return sigs.some((s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
});
}function verify(string $rawBody, string $header, array $secrets, int $tolerance = 300): bool
{
preg_match('/(?:^|,)t=(\d+)/', $header, $m);
preg_match_all('/v1=([0-9a-f]+)/', $header, $v);
$t = (int) ($m[1] ?? 0);
if ($t === 0 || $v[1] === [] || abs(time() - $t) > $tolerance) {
return false;
}
foreach ($secrets as $secret) {
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
foreach ($v[1] as $sig) {
if (hash_equals($expected, $sig)) {
return true;
}
}
}
return false;
}import hashlib, hmac, re, time
def verify(raw_body: bytes, header: str, secrets: list[str], tolerance: int = 300) -> bool:
m = re.search(r"(?:^|,)t=(\d+)", header)
sigs = re.findall(r"v1=([0-9a-f]+)", header)
if not m or not sigs:
return False
t = int(m.group(1))
if abs(time.time() - t) > tolerance:
return False
for secret in secrets:
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
if any(hmac.compare_digest(expected, s) for s in sigs):
return True
return Falseimport (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"math"
"strconv"
"strings"
"time"
)
func verify(rawBody []byte, header string, secrets []string, tolerance time.Duration) bool {
var t int64
var sigs []string
for _, part := range strings.Split(header, ",") {
k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
switch k {
case "t":
t, _ = strconv.ParseInt(v, 10, 64)
case "v1":
sigs = append(sigs, v)
}
}
if t == 0 || len(sigs) == 0 || math.Abs(float64(time.Now().Unix()-t)) > tolerance.Seconds() {
return false
}
for _, secret := range secrets {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(t, 10) + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
for _, s := range sigs {
if hmac.Equal([]byte(s), []byte(expected)) {
return true
}
}
}
return false
}require "openssl"
def verify(raw_body, header, secrets, tolerance: 300)
t = header[/(?:^|,)t=(\d+)/, 1].to_i
sigs = header.scan(/v1=([0-9a-f]+)/).flatten
return false if t.zero? || sigs.empty? || (Time.now.to_i - t).abs > tolerance
secrets.any? do |secret|
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
sigs.any? { |s| s.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(expected, s) }
end
endResponding
Answer within your endpoint's timeout (up to 10 seconds on the free plan, 30 on Pro and Max). Do the work after you have answered: queue the payload and return.
An endpoint has one of two success modes:
| Mode | Delivered when |
|---|---|
http_2xx (default) | Any 2xx status. The body is ignored. |
json_status | A 2xx status and a JSON body with {"status": "success"}. Anything else (another status value, no body, invalid JSON) counts as a failure and is retried — for an endpoint that can accept the request but fail to process it. |
Answering {"status":"success"} with a 200 satisfies both modes. A 3xx is not followed and counts as a failure. A Retry-After header on a failure is honoured, up to a day.
A complete receiver
Each example below is a whole endpoint you can run as it stands. In order, it:
- reads the raw body (in PHP,
php://input: the body is JSON, not a form, so$_POSTstays empty); - checks the signature and answers
400when it does not match; - decodes the JSON into something you can use straight away: an object, a dict or a hash, a struct in Go;
- answers a
webhook.test(the Test button) without processing it; - checks the
Idempotency-Key, and answers a retry it has already handled with success, so the retries stop; - hands the message on, remembers the key, and answers
{"status":"success"}, which satisfies both success modes.
The three placeholders (already processed, mark processed, handle) are where your own code goes. Remember a key only once its message is safely handed on: if anything fails before then, answer an error and the delivery is retried. Keep keys for longer than the longest retry schedule (3 days). Set M2A_SECRET to the endpoint's secret, and M2A_SECRET_PREVIOUS to the old one for the 24 hours after a rotation.
// npm install express · run: M2A_SECRET=whsec_… node server.mjs
import express from 'express';
import crypto from 'node:crypto';
// rawBody: the request body BYTES as received — never a re-serialised object.
export function verify(rawBody, header, secrets, toleranceSeconds = 300) {
const t = Number((header.match(/(?:^|,)t=(\d+)/) || [])[1]);
const sigs = [...header.matchAll(/v1=([0-9a-f]+)/g)].map((m) => m[1]);
if (!t || !sigs.length || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
return secrets.some((secret) => {
const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex');
return sigs.some((s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
});
}
// Both secrets for the 24 hours after a rotation; just M2A_SECRET otherwise.
const SECRETS = [process.env.M2A_SECRET, process.env.M2A_SECRET_PREVIOUS].filter(Boolean);
// The Idempotency-Key is the same on every retry of one delivery.
async function alreadyProcessed(key) {
return false; // TODO: look the key up in your store
}
async function markProcessed(key) {
// TODO: store the key
}
async function handle(payload) {
// TODO: hand the message to your own code — a job queue, a table. Keep it quick:
// answer first, do slow work afterwards. If this throws, the delivery is retried.
}
const app = express();
// express.raw keeps the body as bytes: the signature is over exactly those bytes.
app.post('/mail', express.raw({ type: 'application/json', limit: '12mb' }), async (req, res) => {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
if (!verify(raw, req.get('X-Mail2app-Signature') || '', SECRETS)) {
return res.status(400).send('bad signature');
}
const payload = JSON.parse(raw.toString('utf8')); // an object: payload.message.subject
if (payload.event === 'webhook.test') {
return res.json({ status: 'success' }); // the Test button: nothing to process
}
const key = req.get('Idempotency-Key') || '';
if (await alreadyProcessed(key)) {
return res.json({ status: 'success' }); // a retry of one already handled
}
// payload.message.from.email, payload.message.subject, payload.message.text, payload.attachments, …
await handle(payload);
await markProcessed(key);
res.json({ status: 'success' });
});
app.listen(3000);<?php
// mail.php — the body is JSON, not a form: $_POST stays empty, read php://input.
function verify(string $rawBody, string $header, array $secrets, int $tolerance = 300): bool
{
preg_match('/(?:^|,)t=(\d+)/', $header, $m);
preg_match_all('/v1=([0-9a-f]+)/', $header, $v);
$t = (int) ($m[1] ?? 0);
if ($t === 0 || $v[1] === [] || abs(time() - $t) > $tolerance) {
return false;
}
foreach ($secrets as $secret) {
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
foreach ($v[1] as $sig) {
if (hash_equals($expected, $sig)) {
return true;
}
}
}
return false;
}
// The Idempotency-Key is the same on every retry of one delivery.
function alreadyProcessed(string $key): bool
{
return false; // TODO: look the key up in your store
}
function markProcessed(string $key): void
{
// TODO: store the key
}
function handle(object $payload): void
{
// TODO: hand the message to your own code — a job queue, a table. Keep it quick:
// answer first, do slow work afterwards. If this throws, the delivery is retried.
}
/** @return array{int, string} the status and body to answer with */
function receive(string $raw, array $server): array
{
$success = '{"status":"success"}';
// Both secrets for the 24 hours after a rotation; just M2A_SECRET otherwise.
$secrets = array_values(array_filter([getenv('M2A_SECRET'), getenv('M2A_SECRET_PREVIOUS')]));
if (!verify($raw, $server['HTTP_X_MAIL2APP_SIGNATURE'] ?? '', $secrets)) {
return [400, 'bad signature'];
}
$payload = json_decode($raw); // an object: $payload->message->subject
if ($payload->event === 'webhook.test') {
return [200, $success]; // the Test button: nothing to process
}
$key = $server['HTTP_IDEMPOTENCY_KEY'] ?? '';
if (alreadyProcessed($key)) {
return [200, $success]; // a retry of one already handled
}
// $payload->message->from->email, $payload->message->subject, $payload->message->text, $payload->attachments, …
handle($payload);
markProcessed($key);
return [200, $success];
}
[$status, $body] = receive((string) file_get_contents('php://input'), $_SERVER);
http_response_code($status);
header('Content-Type: ' . ($status === 200 ? 'application/json' : 'text/plain'));
echo $body;# pip install flask · run: M2A_SECRET=whsec_… flask --app mail run
import json, os
from flask import Flask, jsonify, request
import hashlib, hmac, re, time
def verify(raw_body: bytes, header: str, secrets: list[str], tolerance: int = 300) -> bool:
m = re.search(r"(?:^|,)t=(\d+)", header)
sigs = re.findall(r"v1=([0-9a-f]+)", header)
if not m or not sigs:
return False
t = int(m.group(1))
if abs(time.time() - t) > tolerance:
return False
for secret in secrets:
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
if any(hmac.compare_digest(expected, s) for s in sigs):
return True
return False
# Both secrets for the 24 hours after a rotation; just M2A_SECRET otherwise.
SECRETS = [s for s in (os.environ.get("M2A_SECRET"), os.environ.get("M2A_SECRET_PREVIOUS")) if s]
# The Idempotency-Key is the same on every retry of one delivery.
def already_processed(key: str) -> bool:
return False # TODO: look the key up in your store
def mark_processed(key: str) -> None:
pass # TODO: store the key
def handle(payload: dict) -> None:
# TODO: hand the message to your own code — a job queue, a table. Keep it quick:
# answer first, do slow work afterwards. If this raises, the delivery is retried.
pass
app = Flask(__name__)
@app.post("/mail")
def mail():
raw = request.get_data() # the exact bytes: the signature is over these
if not verify(raw, request.headers.get("X-Mail2app-Signature", ""), SECRETS):
return "bad signature", 400
payload = json.loads(raw) # a dict: payload["message"]["subject"]
if payload["event"] == "webhook.test":
return jsonify(status="success") # the Test button: nothing to process
key = request.headers.get("Idempotency-Key", "")
if already_processed(key):
return jsonify(status="success") # a retry of one already handled
# payload["message"]["from"]["email"], payload["message"]["subject"], payload["message"]["text"], payload["attachments"], …
handle(payload)
mark_processed(key)
return jsonify(status="success")// run: M2A_SECRET=whsec_… go run main.go (Go 1.22 or later)
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func verify(rawBody []byte, header string, secrets []string, tolerance time.Duration) bool {
var t int64
var sigs []string
for _, part := range strings.Split(header, ",") {
k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
switch k {
case "t":
t, _ = strconv.ParseInt(v, 10, 64)
case "v1":
sigs = append(sigs, v)
}
}
if t == 0 || len(sigs) == 0 || math.Abs(float64(time.Now().Unix()-t)) > tolerance.Seconds() {
return false
}
for _, secret := range secrets {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(t, 10) + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
for _, s := range sigs {
if hmac.Equal([]byte(s), []byte(expected)) {
return true
}
}
}
return false
}
// The fields most receivers use; add any others from the payload reference.
// Keys you leave out are ignored, so new keys never break you.
type Address struct {
Name *string `json:"name"`
Email string `json:"email"`
}
type Attachment struct {
Filename string `json:"filename"`
ContentType string `json:"content_type"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
URL string `json:"url"`
ContentBase64 string `json:"content_base64"`
}
type Payload struct {
Event string `json:"event"`
MessageID string `json:"message_id"`
Inbox struct {
ID string `json:"id"`
Address string `json:"address"`
} `json:"inbox"`
Message struct {
From Address `json:"from"`
To []Address `json:"to"`
Subject string `json:"subject"`
Text string `json:"text"`
HTML string `json:"html"`
} `json:"message"`
Attachments []Attachment `json:"attachments"`
}
// The Idempotency-Key is the same on every retry of one delivery.
func alreadyProcessed(key string) bool {
return false // TODO: look the key up in your store
}
func markProcessed(key string) {
// TODO: store the key
}
func handle(p Payload) error {
// TODO: hand the message to your own code — a job queue, a table. Keep it quick:
// answer first, do slow work afterwards. An error here means the delivery is retried.
return nil
}
// Both secrets for the 24 hours after a rotation; just M2A_SECRET otherwise.
var secrets = nonEmpty(os.Getenv("M2A_SECRET"), os.Getenv("M2A_SECRET_PREVIOUS"))
func mail(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12<<20)) // the exact bytes
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
if !verify(raw, r.Header.Get("X-Mail2app-Signature"), secrets, 5*time.Minute) {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
var payload Payload // a struct: payload.Message.Subject
if err := json.Unmarshal(raw, &payload); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
if payload.Event == "webhook.test" {
success(w) // the Test button: nothing to process
return
}
key := r.Header.Get("Idempotency-Key")
if alreadyProcessed(key) {
success(w) // a retry of one already handled
return
}
// payload.Message.From.Email, payload.Message.Subject, payload.Message.Text, payload.Attachments, …
if err := handle(payload); err != nil {
http.Error(w, "try again", http.StatusInternalServerError)
return
}
markProcessed(key)
success(w)
}
func success(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"success"}`))
}
func nonEmpty(values ...string) []string {
var out []string
for _, v := range values {
if v != "" {
out = append(out, v)
}
}
return out
}
func main() {
http.HandleFunc("POST /mail", mail)
log.Fatal(http.ListenAndServe(":3000", nil))
}# app/controllers/mail2app_webhooks_controller.rb
# config/routes.rb: post "/mail", to: "mail2app_webhooks#create"require "openssl"
# ActionController::API has no CSRF check. On ActionController::Base, add skip_forgery_protection.
class Mail2appWebhooksController < ActionController::API
# Both secrets for the 24 hours after a rotation; just M2A_SECRET otherwise.
SECRETS = [ENV["M2A_SECRET"], ENV["M2A_SECRET_PREVIOUS"]].compact.reject(&:empty?)
def create
raw = request.raw_post # the exact bytes: the signature is over these
return head :bad_request unless verify(raw, request.headers["X-Mail2app-Signature"].to_s, SECRETS)
payload = JSON.parse(raw) # a Hash: payload["message"]["subject"]
if payload["event"] == "webhook.test"
return render json: { status: "success" } # the Test button: nothing to process
end
key = request.headers["Idempotency-Key"].to_s
return render json: { status: "success" } if already_processed?(key) # a retry of one already handled
# payload["message"]["from"]["email"], payload["message"]["subject"], payload["message"]["text"], payload["attachments"], …
handle(payload)
mark_processed(key)
render json: { status: "success" }
end
private
# The Idempotency-Key is the same on every retry of one delivery.
def already_processed?(key)
false # TODO: look the key up in your store
end
def mark_processed(key)
# TODO: store the key
end
def handle(payload)
# TODO: hand the message to your own code — Active Job, a table. Keep it quick:
# answer first, do slow work afterwards. If this raises, the delivery is retried.
end
def verify(raw_body, header, secrets, tolerance: 300)
t = header[/(?:^|,)t=(\d+)/, 1].to_i
sigs = header.scan(/v1=([0-9a-f]+)/).flatten
return false if t.zero? || sigs.empty? || (Time.now.to_i - t).abs > tolerance
secrets.any? do |secret|
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
sigs.any? { |s| s.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(expected, s) }
end
end
endRetries
A delivery that fails — a non-2xx, a timeout, a connection refused, a wrong body in json_status mode — is tried again on a schedule set by your plan, with a little jitter so retries do not arrive in lockstep:
| Plan | Attempts | Wait before each retry | Spread over |
|---|---|---|---|
| Free | 5 | at once, 30 s, 2 min, 10 min, 30 min | 43 minutes |
| Basic | 7 | at once, 30 s, 2 min, 10 min, 30 min, 1 h, 2 h | 4 hours |
| Pro | 10 | at once, 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h, 8 h, 8 h | a day |
| Max | 12 | at once, 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h, 8 h, 8 h, 24 h, 24 h | 3 days |
Every attempt carries the same Idempotency-Key and X-Mail2app-Delivery-Id, and a new X-Mail2app-Attempt / X-Mail2app-Attempt-Id. When the schedule is exhausted the delivery is marked as given up and the message, if no other endpoint still needs it, is deleted.
An endpoint that fails twenty deliveries in a row over at least a day is switched off and you are emailed; fix it and switch it back on from its page. A URL that cannot be delivered to at all (a private address, a host that does not resolve, a certificate that does not verify) is switched off after three attempts. Deliveries that were waiting for a switched-off endpoint are cancelled; new mail to its addresses is held until an endpoint is attached again.
Held mail
Some mail is accepted and kept, encrypted, without being delivered yet. The payload is not sent; the message shows as held with a reason:
| Reason | Why | Released |
|---|---|---|
daily_cap | The address has had its day's messages (20 on the free plan). Up to about twice the cap is held; beyond that the sender is told to try later. | At 00:00 UTC, in order of arrival, within the new day's cap — or at once when you move to a plan that allows it. |
no_webhook | The address has no endpoint attached, or the endpoints the rule that took the message sends to are all switched off. | When one is attached or switched back on. |
no_match | No routing rule matched, and "Otherwise" has no endpoint and is set to hold. | When you add or change a rule, or attach an endpoint, that would take it. |
paused | The address, or its subdomain, is paused (by you, or by a plan change). | When it is resumed. |
account | The account's email is not verified yet. | When it is. |
Mail held for seven days without being released is discarded and counted as failed. Your dashboard shows what is held and why. Mail a routing rule discards is not held: it shows as dropped, discarded, with the rule that did it.
The live inspector
Every plan can watch an address for a while. Open the address, start the inspector, and each message that arrives during the window appears as it happens — the parsed message, then each delivery with the exact request we sent (headers, signature, body) and what your endpoint answered. It is the fastest way to see why a signature does not verify or what a 422 from your side said.
A window is 15 minutes on the free plan (60 on Pro) and closes itself. What the inspector captured stays visible for the window; after it, content is kept only on plans with retention.
Limits
Addresses, subdomains, webhooks per address, endpoints, messages per address per day, message size, attachment handling, retention, the delivery log, inspector time, retries and the webhook timeout all depend on the plan. The full table is on the pricing page; a signed-in account sees its own numbers and usage on its billing page.
Limits are enforced where they bite: creating an address past the cap is refused with a message; a message over the daily cap is held; an attachment setting above the plan is clamped at delivery (and restored when the plan grows); content older than retention is deleted.
The API
Everything the pages do, your code can do, with an API token (issue one on the API tokens page, under your account menu; give it write scope to create things — the token is shown once, and you are emailed whenever one is issued). Send it as Authorization: Bearer …. Writes take a JSON body.
A write you must not repeat — a create, a secret rotation, a test send, a redelivery — can carry an Idempotency-Key header (any string of your choosing, up to 255 characters). Retry with the same key and the same request after a timeout or a lost reply and you get the first answer again, marked Idempotency-Replayed: true, with nothing done twice; the key is remembered for 24 hours. The same key with a different request is refused with 422.
Provision an address in one call
For software that wants an inbox of its own without a person clicking through the pages: one call creates the address, the endpoint and the attachment, keyed by a name you choose, and is safe to repeat.
curl -X POST https://mail2app.com/api/m2a/provision \
-H "Authorization: Bearer m2a_xxxxxxxx_…" \
-H "Content-Type: application/json" \
-d '{"key": "bills", "label": "Supplier bills", "webhook_url": "https://api.yourapp.example/mail", "success_mode": "json_status"}'{
"success": true,
"inbox_id": "9b8a7c6d-…",
"address": "[email protected]",
"webhook_id": "4e5f6a7b-…",
"secret": "whsec_…",
"created": true
}| Call | Does |
|---|---|
POST /api/m2a/provision | key (letters, digits, . _ - :), webhook_url, optional label, success_mode, attachment_mode, inline_max_bytes, url_ttl_seconds, include_html, include_raw, timeout_seconds. On a plan with one address, the free address is adopted for the key. |
GET /api/m2a/provision/{key} | {inbox_id, address, webhook_id, state} |
POST /api/m2a/provision/{key}/rotate-secret | A new secret (the old one keeps verifying for 24 hours) |
POST /api/m2a/provision/{key}/test | Sends a webhook.test delivery from a mail server and returns what your endpoint answered; when no server has answered within 25 s you get 202 with a command id to poll at GET /api/m2a/commands/{id} |
DELETE /api/m2a/provision/{key} | Removes the endpoint and the named address (the free address only forgets the key) |
The rest
/api/m2a/overview, /api/m2a/inboxes/{id}/… (stats, live messages, webhooks, rules, sample, inspector, release, pause), /api/m2a/webhooks/{id}/… (secret, rotate, test, enable, disable), /api/m2a/messages/{id}, /api/m2a/deliveries/{id}/exchange and …/redeliver — the same calls the pages make. Anything that acts on mail (a release, a redelivery, a test send) runs on the mail servers: the call answers 202 with a command id, and GET /api/m2a/commands/{id} reports its status and result once they have answered. /api/m2a/domains and …/{id}/check list, add and check domains (your own domain). Addresses, subdomains and endpoints are also plain REST resources at /api/mail_inboxes, /api/mail_domains and /api/mail_webhooks. Every response is JSON with a success flag; errors carry an error message and, for a refused write, a fields map.
From a bspkfw project
Applications built on the bspkfw framework have mail2app built in: three configuration lines and one hook, and the framework provisions the address, receives the webhook at /api/_inbound_mail/webhook, verifies the signature, dedupes, and hands each message to your code from a job.
; config.ini
[inbound_mail]
provider = mail2app
api_base = https://mail2app.com
api_token = m2a_xxxxxxxx_… ; an API token with write scope// Once, from a setup script or a settings page: an address of your own.
$inbox = \Bspkfw\Core\InboundMail::provision('bills', ['label' => 'Supplier bills']);
// ['address' => '[email protected]', 'inbox_id' => …, 'webhook_id' => …, 'created' => true]
// Then, in <Project>\Project — called by a job for every message, at least once:
public static function inboundMailReceived(string $key, \Bspkfw\Core\InboundMessage $m): void
{
if ($key !== 'bills') return;
foreach ($m->attachments() as $a) { // real attachments; signature logos left out
$pdf = $a->bytes(); // decoded, or fetched from its link, SHA-256 checked
Bills::fileFromEmail($m->from['email'], $m->subject, $pdf, keyedOn: $m->deliveryId);
}
}The framework's own guide has the rest: bspkfw/CLAUDE/INBOUND-MAIL.md — rotating the secret, sending a test, the simulate() seam for your tests, and the settings section that lists your inboxes.
Testing
- Send yourself a sample. On your dashboard, one click sends a sample message to your address from our side. Watch it arrive and be delivered; the timeline shows the status your endpoint answered and how long it took.
- Test an endpoint. On an endpoint's page, Test send posts a signed
webhook.testdelivery and shows the request and the reply, headers included. - Open the inspector on an address while you forward a real message, and read the exact exchange.
- During development, an endpoint on a public HTTPS URL is required; a tunnel to your machine (any of the usual ones) works. Private addresses and plain
http://are refused.
Questions, or something missing from this page? [email protected].