Inbound mail
Inbound mail is in an invite-only preview: the endpoints below answer 403 with {"error": "inbound_not_in_plan"} until your organization takes part, and on a plan without inbound mail (Free, or while your organization is in the sandbox). Received mail counts towards your plan's monthly volume like a sent message, see Usage.
Postilio can receive mail for you. Point the MX record of a receiving domain at Postilio, add a route for the addresses that should take mail, and every message that arrives comes to your webhook endpoint as an inbound.received.v1 event: parsed, with its authentication results and spam score. You can also fetch it through the API while its content is kept.
Reading needs the inbound:read scope (a test key can have it); everything that changes something needs inbound:manage, which includes reading.
Receiving domains
A receiving domain is a name your project takes mail on, best a subdomain that receives no mail today (inbound.example.com, reply.example.com). It is proven by a verified sending domain of the project at or above it, or by a TXT record with a token: the answer's records lists what to add at your DNS provider, the TXT token when it needs one and the MX record. Postilio's MX has more than one name: an MX record at an older one (inbound.postilio.eu) keeps working, and the MX record then carries newValue with today's name once Postilio recommends the move (Migrate your domain).
curl https://api.postilio.eu/v1/inbound/domains \
-H "Authorization: Bearer $POSTILIO_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "inbound.example.com" }'
A name that already has MX records of another party answers 409 with {"error": "inbound_domain_has_mx"} and the hosts in message: mail to it would stop arriving there. Send "confirmExistingMx": true to go ahead anyway.
| Status | Error | When |
|---|---|---|
409 | inbound_domain_exists | the project has the name already |
409 | inbound_domain_taken | another project holds the name |
409 | inbound_domain_limit_reached | your organization has the receiving domains its plan allows (5 by default), or the project has 20 |
422 | inbound_domain_reserved | a name of Postilio's own |
Postilio checks the DNS of every domain regularly; POST /v1/inbound/domains/{id}/check checks one now, at most once a minute (429 with Retry-After). GET /v1/inbound/domains lists them, GET /v1/inbound/domains/{id} gets one, and DELETE /v1/inbound/domains/{id} removes one: mail to it is refused from then on.
| Status | Meaning |
|---|---|
pending | waiting for its proof or its MX record |
active | takes mail |
failing | its MX record or proof went missing; it still takes mail for a while |
suspended | its proof was gone too long; mail is refused |
Routes
A route says which addresses of a receiving domain take mail and where it goes. An address without a route is refused while the sender is still connected (550 5.1.1); Postilio never sends a bounce of its own afterwards.
curl https://api.postilio.eu/v1/inbound/routes \
-H "Authorization: Bearer $POSTILIO_KEY" \
-H "Content-Type: application/json" \
-d '{ "domainId": "01a15270-3c4d-7e5f-8a6b-7c8d9e0f1a2b", "match": "exact", "value": "support", "action": "webhook", "endpointId": "01a0f3c2-77aa-7c1e-9d2f-0b1c2d3e4f50" }'
matchisexact(the local partvalue, sosupporttakessupport@…),prefix(every local part that starts withvalue:reply+takesreply+4821@…) orcatch_all(every other address,valueempty). An exact route wins over a prefix, the longest prefix over a shorter one, a prefix over the catch-all. A domain has no catch-all until you make one; it also takes every guess a spammer makes, and each message counts in your monthly volume.actioniswebhook(deliver toendpointId, an endpoint of the project in the same mode as the route; the route turns theinboundevent on there) orstore(keep it for the API only, until its content goes).modeislive(the default) ortest: a test route delivers to a test endpoint. Mail is always real; the mode separates the streams, and a test key sees only the mail of test routes.spamActionisfilter_reject(the default: hold back what rspamd would reject) ordeliver_all.senderAllowtakes mail only from these senders, addresses or@domain, at most 100, matched on theFromheader;requireDmarconly mail that passes DMARC. Held-back mail (statusfiltered) gets no webhook and does not count in your monthly volume.
| Status | Error | When |
|---|---|---|
409 | inbound_route_exists | the domain has a route for this pattern already |
409 | inbound_route_limit_reached | the project has 100 routes |
422 | inbound_domain_not_found | domainId is not a receiving domain of the project |
422 | webhook_endpoint_not_found | endpointId is not a webhook endpoint of the project |
422 | webhook_endpoint_mode_mismatch | the endpoint is a test endpoint and the route a live one, or the other way round |
PATCH /v1/inbound/routes/{id} changes only the fields you send: action, endpointId, spamAction, senderAllow, requireDmarc, description, and paused. A paused route asks senders to try again later (450 4.2.1), so nothing is lost while you fix your endpoint. The domain, match, value and mode stay; make a new route to change them.
curl -X PATCH https://api.postilio.eu/v1/inbound/routes/$ROUTE_ID \
-H "Authorization: Bearer $POSTILIO_KEY" \
-H "Content-Type: application/json" \
-d '{ "paused": true }'
GET /v1/inbound/routes lists the project's routes, GET /v1/inbound/routes/{id} gets one and DELETE /v1/inbound/routes/{id} removes one.
Received messages
curl "https://api.postilio.eu/v1/inbound/messages?status=failed&limit=20" \
-H "Authorization: Bearer $POSTILIO_KEY"
GET /v1/inbound/messages lists the newest first, with what is known about each message but never its content: the envelope, from, subject (only when the project keeps subjects), messageId, inReplyTo, relatedEmailId, the size, the number of attachments, the spam score and verdict, the DMARC result, the status and when the content goes. Filter with status and route (a route id); for the next page pass the answer's next as before.
| Status | Meaning |
|---|---|
received | arrived, not read yet |
delivering | its webhook is on its way |
delivered | your endpoint took it |
failed | your endpoint did not take it within the retries, or its content went first |
stored | kept for the API: a store route, or a route without a working endpoint |
filtered | held back by its route (filteredReason: sender_not_allowed, dmarc_failed or spam) |
expired | its content went before anything was done with it (expiredReason: content_expired or lost_in_restore) |
GET /v1/inbound/messages/{id} adds content: the data of its inbound.received.v1 event, the same JSON your endpoint got (also for a message that was held back or stored). Once the content went, content is null and contentDeleted is true; the rest stays as long as the project keeps its log.
curl https://api.postilio.eu/v1/inbound/messages/$INBOUND_ID/attachments/0 \
-H "Authorization: Bearer $POSTILIO_KEY" -o photo.jpg
GET /v1/inbound/messages/{id}/attachments/{index} downloads one attachment by its index, always as a download (Content-Disposition: attachment, X-Content-Type-Options: nosniff): never open one in a browser as it comes. Nothing is scanned for viruses. GET /v1/inbound/messages/{id}/raw downloads the message exactly as it arrived (message/rfc822), also when text or html in the event were cut.
Redeliver
curl -X POST https://api.postilio.eu/v1/inbound/messages/$INBOUND_ID/redeliver \
-H "Authorization: Bearer $POSTILIO_KEY"
Sends the event once more, now, to the endpoint the message's route has today, with the same webhook-id and the same body: your receiver may drop it as a repeat, so drop it only once you stored the first one. It is one attempt, without retries. 409 with delivery_still_pending while a delivery to that endpoint is still being tried, endpoint_paused while the endpoint is paused, and inbound_route_has_no_endpoint when the route stores mail, has no endpoint any more or was deleted, or the endpoint does not take inbound events.
Content is kept briefly
The content of a message (its parsed form, attachments and raw mail) is kept 24 hours after it was delivered, and 4 days after it arrived at the latest; a held-back message 24 hours. contentExpiresAt says when. After that, the attachment, raw and redeliver endpoints answer 410 with {"error": "inbound_content_deleted"}, and a delivery still waiting for its turn fails with content_expired without sending anything. Download what you need when the event arrives.
DELETE /v1/inbound/messages/{id}/content deletes the content now; the metadata stays. A message that was not delivered yet becomes expired. Deleting content that is gone already answers 204 too.
curl -X DELETE https://api.postilio.eu/v1/inbound/messages/$INBOUND_ID/content \
-H "Authorization: Bearer $POSTILIO_KEY"
Downloading an attachment or the raw message, redelivering and deleting content are in your organization's audit log, with the API key as the actor; the content itself never is.
Receive the event
A receiver checks the signature over the raw body, drops a repeat by its webhook-id (the inboundId), answers 2xx quickly, and fetches the attachments it needs with an API key while they are kept. An attachment that answers 410 is gone: log it and carry on, never retry it. Each example below uses the verifier from Verifying the signature next to it, and keeps the ids it saw in memory; keep them in your database instead, so a restart does not forget them.
Inbound mail is untrusted input: never show its html without sanitizing it, and trust from only with auth.dmarc.result pass.
Node
// Receives inbound mail from Postilio: checks the signature, drops a repeat, answers at once, then fetches the
// attachments with an API key. Node 22, no packages. Run: PORT=3000 node inbound-receiver.mjs
import { createServer } from 'node:http';
import { verifyWebhook } from './verify.mjs';
const secret = process.env.POSTILIO_WEBHOOK_SECRET;
const apiKey = process.env.POSTILIO_KEY;
const seen = new Set(); // the webhook-ids taken; keep them in your database
createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
const id = req.headers['webhook-id'] ?? '';
const signed = { id, timestamp: req.headers['webhook-timestamp'] ?? '', signature: req.headers['webhook-signature'] ?? '' };
if (!verifyWebhook(secret, signed, body)) {
res.writeHead(401).end();
return;
}
if (seen.has(id)) {
console.log(`repeat ${id}`);
res.writeHead(204).end();
return;
}
const event = JSON.parse(body);
seen.add(id); // store the event itself here too, before answering
res.writeHead(204).end();
if (event.type === 'inbound.received.v1') {
handleMail(event.data).catch((error) => console.error(error));
}
});
}).listen(Number(process.env.PORT ?? 3000));
async function handleMail(mail) {
// Trust the sender only when DMARC passed; treat the text and html as untrusted input.
console.log(`mail ${mail.inboundId} from ${mail.from?.address} (dmarc ${mail.auth?.dmarc?.result ?? 'none'})`);
for (const attachment of mail.attachments) {
const response = await fetch(attachment.url, { headers: { Authorization: `Bearer ${apiKey}` } });
if (response.status === 410) {
console.log(`attachment ${attachment.index} gone`); // the content expired: never retry it
continue;
}
if (!response.ok) {
throw new Error(`attachment ${attachment.index}: ${response.status}`);
}
const bytes = Buffer.from(await response.arrayBuffer());
console.log(`attachment ${attachment.index} ${attachment.filename} ${bytes.length} bytes`);
}
}
Python
"""Receives inbound mail from Postilio: checks the signature, drops a repeat, answers at once, then fetches the
attachments with an API key. Standard library only. Run: PORT=3000 python3 inbound_receiver.py"""
import json
import os
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from verify import verify_webhook
SECRET = os.environ["POSTILIO_WEBHOOK_SECRET"]
API_KEY = os.environ["POSTILIO_KEY"]
seen = set() # the webhook-ids taken; keep them in your database
def handle_mail(mail):
# Trust the sender only when DMARC passed; treat the text and html as untrusted input.
dmarc = (mail.get("auth", {}).get("dmarc") or {}).get("result", "none")
print(f"mail {mail['inboundId']} from {(mail.get('from') or {}).get('address')} (dmarc {dmarc})", flush=True)
for attachment in mail["attachments"]:
request = urllib.request.Request(attachment["url"], headers={"Authorization": f"Bearer {API_KEY}"})
try:
with urllib.request.urlopen(request, timeout=30) as response:
content = response.read()
except urllib.error.HTTPError as e:
if e.code == 410:
print(f"attachment {attachment['index']} gone", flush=True) # the content expired: never retry it
continue
raise
print(f"attachment {attachment['index']} {attachment['filename']} {len(content)} bytes", flush=True)
class Receiver(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
msg_id = self.headers.get("webhook-id", "")
if not verify_webhook(SECRET, msg_id, self.headers.get("webhook-timestamp", ""), self.headers.get("webhook-signature", ""), body):
self.send_response(401)
self.end_headers()
return
if msg_id in seen:
print(f"repeat {msg_id}", flush=True)
else:
event = json.loads(body)
seen.add(msg_id) # store the event itself here too, before answering
if event["type"] == "inbound.received.v1":
threading.Thread(target=handle_mail, args=(event["data"],)).start()
self.send_response(204)
self.end_headers()
ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Receiver).serve_forever()
C#
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Channels;
namespace Postilio.Webhooks;
/// <summary>
/// Receives inbound mail from Postilio: checks the signature, drops a repeat, answers at once and queues the mail; a
/// background loop (<see cref="RunAsync"/>) fetches the attachments with an API key. Uses WebhookVerifier, no packages.
/// In a minimal API: <c>app.MapPost("/postilio/inbound", async (HttpRequest r) => Results.StatusCode(receiver.Receive(
/// r.Headers["webhook-id"]!, r.Headers["webhook-timestamp"]!, r.Headers["webhook-signature"]!, await new StreamReader(r.Body).ReadToEndAsync())))</c>.
/// </summary>
public sealed class InboundReceiver(string secret, string apiKey, HttpClient http, Action<string> log)
{
private readonly ConcurrentDictionary<string, bool> _seen = new(); // the webhook-ids taken; keep them in your database
private readonly Channel<JsonElement> _mail = Channel.CreateUnbounded<JsonElement>();
/// <summary>The status code to answer: 401 for a wrong signature, else 204 at once.</summary>
public int Receive(string id, string timestamp, string signature, string body)
{
if (!WebhookVerifier.Verify(secret, id, timestamp, signature, body, DateTimeOffset.UtcNow))
{
return 401;
}
if (!_seen.TryAdd(id, true))
{
log($"repeat {id}");
return 204;
}
// Store the event itself here too, before answering.
using var json = JsonDocument.Parse(body);
if (json.RootElement.GetProperty("type").GetString() == "inbound.received.v1")
{
_mail.Writer.TryWrite(json.RootElement.GetProperty("data").Clone());
}
return 204;
}
/// <summary>Handles the queued mail until <paramref name="ct"/> stops it; run it as a background service.</summary>
public async Task RunAsync(CancellationToken ct)
{
while (await _mail.Reader.WaitToReadAsync(ct))
{
await ProcessPendingAsync(ct);
}
}
public async Task ProcessPendingAsync(CancellationToken ct)
{
while (_mail.Reader.TryRead(out var mail))
{
await HandleMailAsync(mail, ct);
}
}
private async Task HandleMailAsync(JsonElement mail, CancellationToken ct)
{
// Trust the sender only when DMARC passed; treat the text and html as untrusted input.
var dmarc = mail.GetProperty("auth").TryGetProperty("dmarc", out var d) && d.ValueKind == JsonValueKind.Object ? d.GetProperty("result").GetString() : "none";
log($"mail {mail.GetProperty("inboundId").GetString()} from {mail.GetProperty("from").GetProperty("address").GetString()} (dmarc {dmarc})");
foreach (var attachment in mail.GetProperty("attachments").EnumerateArray())
{
var index = attachment.GetProperty("index").GetInt32();
using var request = new HttpRequestMessage(HttpMethod.Get, attachment.GetProperty("url").GetString());
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await http.SendAsync(request, ct);
if (response.StatusCode == HttpStatusCode.Gone)
{
log($"attachment {index} gone"); // the content expired: never retry it
continue;
}
response.EnsureSuccessStatusCode();
var bytes = await response.Content.ReadAsByteArrayAsync(ct);
log($"attachment {index} {attachment.GetProperty("filename").GetString()} {bytes.Length} bytes");
}
}
}