Every email test has the same awkward moment: your app has sent a message, and you must wait for it to arrive. The lazy fix is sleep(10), which makes fast tests slow and slow deliveries flaky. The BoltMail /wait endpoint solves this properly with long polling. This guide explains how it behaves and how to build a helper you can trust.
What long polling is
With ordinary polling you ask "anything yet?" every second and mostly hear "no". With long polling you ask once, and the server keeps the connection open until there is something to say or a timeout passes. You get the answer the instant it exists, with one request instead of dozens. That is kinder to your rate limit and faster for your tests.
The request
GET /api/v1/mailboxes/{address}/wait?timeout=25&after_id=0
There are two parameters, both optional:
timeoutis how many seconds to wait, from 1 to 25. The default is 20. The limit exists because web servers and proxies close very long connections.after_idmeans "only tell me about messages with an id higher than this". If you leave it out entirely, BoltMail uses the highest id currently in the mailbox, so you only hear about mail that arrives after your call. That is exactly what you want when you call it right after triggering the email.
The response
When a message arrives you get the messages (up to twenty, oldest first), timed_out: false and a last_id. When the timeout passes with nothing new, you get an empty list, timed_out: true and your after_id echoed back as last_id. In both cases last_id is the value to send as after_id in the next call, which makes a loop trivial and keeps you from ever missing or double-counting a message.
The race condition to avoid
Here is a classic bug. Your test triggers the email, then calls /wait without after_id. If the email was delivered in the few milliseconds between those two steps, the server treats it as already existing and waits for the next one, which never comes. The fix is to remember the position before you trigger the email:
- Call
GET /mailboxes/{address}/messages?limit=1and note the highestid, or use0for a fresh mailbox. - Trigger the email.
- Call
/wait?after_id=THAT_ID.
For a brand-new mailbox that you just created, after_id=0 is always safe.
A reliable helper in Python
import time, requests
def wait_for_email(session, base, address, total_seconds=60, after_id=0, match=None):
deadline = time.time() + total_seconds
while time.time() < deadline:
left = max(1, min(25, int(deadline - time.time())))
r = session.get(f'{base}/mailboxes/{address}/wait',
params={'timeout': left, 'after_id': after_id}, timeout=left + 10)
if r.status_code == 429:
time.sleep(int(r.headers.get('Retry-After', 5)))
continue
r.raise_for_status()
data = r.json()
after_id = data['last_id']
for m in data['messages']:
if match is None or match(m):
return m
raise TimeoutError('no matching email within %d seconds' % total_seconds)
Notice four details. The loop respects a total deadline, not just a single call. Each request asks for no more time than remains. The HTTP client timeout is longer than the server timeout, otherwise your own client gives up first. And a 429 is handled by sleeping for the time the server asks.
The same idea in JavaScript
async function waitForEmail(api, address, { totalMs = 60000, afterId = 0, match = () => true } = {}) {
const end = Date.now() + totalMs;
while (Date.now() < end) {
const secs = Math.max(1, Math.min(25, Math.floor((end - Date.now()) / 1000)));
const r = await api('GET', `/mailboxes/${address}/wait?timeout=${secs}&after_id=${afterId}`);
if (r.status === 429) { await new Promise(s => setTimeout(s, 1000 * Number(r.headers.get('Retry-After') || 5))); continue; }
const data = await r.json();
afterId = data.last_id;
const hit = data.messages.find(match);
if (hit) return hit;
}
throw new Error('no matching email in time');
}
Filtering: not every email is the one you want
A sign-up may send a welcome message and a verification message, or a marketing app may add a promotion. Pass a match function that checks the subject or sender, and keep looping until the right one arrives. Because last_id moves forward each time, ignored messages are never returned twice.
Choosing a sensible total wait
- Transactional email from a well-set-up provider usually arrives within five seconds.
- Allow 30 to 60 seconds in tests, so that a slow provider does not cause false failures.
- Never wait longer than a user would. If a real person would give up after a minute, your test should fail at a minute, because that is a real bug.
Cost and limits
One long-poll call counts as one request against your rate limit and your monthly quota, no matter how long it waits. A test that waits 20 seconds costs one request, whereas polling every second would cost twenty. Each open call also holds a server worker, so do not open hundreds in parallel. If you run a big suite, spread it over several mailboxes and keep concurrency within your plan's per-minute limit.
Long polling versus webhooks
Webhooks push a message to a public URL on your side. They are excellent for production systems, but they need a reachable endpoint, which is awkward on a laptop or inside a locked-down CI runner. Long polling needs nothing but outbound HTTPS, works behind any firewall and is simple to reason about, which is why it is the right tool for tests and scripts.
With a helper like the one above, "wait for the email" becomes a single reliable line in your tests. See the API documentation for the exact response fields.











