Live events

No public endpoint? Read the same events over a stream, or wait for one message at a time.

#The event stream

GET /v1/events/stream is a server-sent events stream. Each frame has the event type, the event id and the Event as JSON.

shell
curl -N https://api.trotta.email/v1/events/stream \
  -H "Authorization: Bearer $TROTTA_MAIL_API_KEY"
A frame
event: message.received
id: evt_1Vb6kRs3
data: {"id":"evt_1Vb6kRs3","type":"message.received","inbox_id":"inb_7Qh2mXc4","data":{...}}

Narrow it with inbox_id and types (comma separated).

#In code

The key goes in the Authorization header, so read the stream with fetch. There is no token in the URL.

typescript
const response = await fetch("https://api.trotta.email/v1/events/stream?types=message.received,message.held", {
  headers: { Authorization: `Bearer ${process.env.TROTTA_MAIL_API_KEY}`, Accept: "text/event-stream" },
});

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  const frames = buffer.split("\n\n");
  buffer = frames.pop() ?? "";
  for (const frame of frames) {
    const data = frame.split("\n").find((line) => line.startsWith("data: "));
    if (!data) continue; // a comment or a keep-alive
    const event = JSON.parse(data.slice(6));
    console.log(event.type, event.data.message?.subject);
  }
}

EventSource cannot set headers, so it is for the signed-in web app only, where the browser sends the session cookie. Never put a key in a page.

#Over a WebSocket

/v1/events/ws carries the same events to the same callers, one Event JSON per frame. The key goes in the Authorization header of the request that opens it. A key in the URL is refused.

typescript
import WebSocket from "ws";

const ws = new WebSocket("wss://api.trotta.email/v1/events/ws?types=message.received", {
  headers: { Authorization: `Bearer ${process.env.TROTTA_MAIL_API_KEY}` },
});
ws.on("message", (frame) => console.log(JSON.parse(String(frame)).type));

In the browser the socket uses the session cookie, and only the web app may open it. A refusal is one frame with error, then a close code: 4400, 4401, 4403 or 4404.

#Resume after a drop

Reconnect with the Last-Event-ID header set to the last id you saw, and the stream continues from there. To catch up after longer downtime, page through GET /v1/events?after=evt_.... A stream ends within a minute of its key being revoked.

#Or wait for one message

For an agent expecting one email, GET /v1/inboxes/{id}/wait is simpler than a stream. It returns the next delivered message, or times out after up to 60 seconds.

shell
curl -G https://api.trotta.email/v1/inboxes/inb_7Qh2mXc4/wait \
  -d has_code=true -d timeout=60 \
  -H "Authorization: Bearer $TROTTA_MAIL_API_KEY"