Temp Mail API for Developers: Automate Sign-up and OTP Email Tests

Published

The TempMailo API gives your code a real inbox for a few minutes. One POST request creates an address, and GET requests return whatever arrives there as JSON. That lets you test your own sign-up, login-code and password-reset emails end to end, the way a new user receives them. A free account comes with an API key: 100 new addresses a day and 60 requests a minute. Addresses live 10 or 60 minutes and only receive mail.

This guide goes from the first curl request to a sign-up test running in CI. Every field name and limit below was checked against the API documentation on December 2, 2026.

One test, end to end

Sequence diagram: the test creates an address, the app sends an email to it, the test polls the API, reads the message and deletes the address
Ten steps of one sign-up test. Steps 5 and 6 repeat until the email arrives.

Your app doesn't change for this. It sends the email through the same mail provider and templates it uses in production, to an address that really exists. The test reads what arrived and uses it the way a person would: it types the code or opens the link. If the email never comes, the test fails, and you hear about it before your users do.

That's the difference from a mocked mailer. A mock shows that your code called "send". A real inbox shows that the email left your provider, reached an outside address and carries a code or link that works.

What you can test this way

Typical email tests and the API methods they use
ScenarioWhat the test checksMethods
Sign-up confirmationThe email arrives and its link confirms the accountcreate, messages, message
Login codes (OTP)The code arrives, works once and stops working when it shouldmessages with after, message
Password resetThe link opens the right page, and the old password stops workingmessages, message
Email changeBoth the old and the new address get the right noticecreate twice
Invoices and reportsThe attachment is there, with the right name and typemessage, attachment
HeadersFrom, Reply-To, List-Unsubscribe and DKIM-Signature are setsource
Smoke test after a deployThe sign-up email still arrives after a releaseThe whole flow, once per deploy

Get a key

  1. Create a free account on the sign-up page and confirm your email address.
  2. Open the API key page in your account and create a key. It starts with tmk_.
  3. Store it in an environment variable or in your CI secrets, never in the repository. An account has one key, and when you create a new one, the old key stops working at once.

Quick start with curl

Create an address that lives 10 minutes. The client field is optional and names your test suite.

export TEMPMAILO_KEY=tmk_your_key_here

curl -s -X POST https://tempmailo.co/api/v2/create/ \
  -H "X-Api-Key: $TEMPMAILO_KEY" \
  -d lifetime=600 -d client="signup-tests 1.0"

The reply holds the address, its token and what is left of your quota. The address here is a placeholder, and yours will be on one of our domains.

{
  "ok": true,
  "time": 1796227215,
  "token": "a2b66f7ea8618fcfe56512421f14ab3b",
  "mailbox": {
    "email": "ed9qfemu@example.org",
    "login": "ed9qfemu",
    "domain": "example.org",
    "created": 1796227215,
    "expired": 1796227815,
    "lifetime": 600
  },
  "quota": {
    "create_day": {"used": 1, "limit": 100, "reset": 1796256000},
    "create_hour": {"used": 1, "limit": 100, "reset": 1796230800}
  }
}

Now sign up in your app with that address. Then ask for the mailbox contents, sending both the key and the token:

TOKEN=a2b66f7ea8618fcfe56512421f14ab3b

curl -s https://tempmailo.co/api/v2/messages/ \
  -H "X-Api-Key: $TEMPMAILO_KEY" \
  -H "Authorization: Bearer $TOKEN"
{
  "ok": true,
  "time": 1796227241,
  "mailbox": {"email": "ed9qfemu@example.org", "expired": 1796227815, "...": "..."},
  "messages": [
    {"id": 3, "from": "noreply@app.example", "from_name": "Example App",
     "subject": "Your verification code", "preview": "Your code is 482913",
     "date": 1796227238, "unread": true, "attachments": 0}
  ]
}

The list gives a short preview of each message, newest first. message returns one message in full: the text and HTML parts, the recipients and the attachments, and it marks the message as read. When the test is done, delete removes the address together with its mail and token.

curl -s "https://tempmailo.co/api/v2/message/?id=3" \
  -H "X-Api-Key: $TEMPMAILO_KEY" \
  -H "Authorization: Bearer $TOKEN"

curl -s -X POST https://tempmailo.co/api/v2/delete/ \
  -H "X-Api-Key: $TEMPMAILO_KEY" \
  -H "Authorization: Bearer $TOKEN"

Methods you'll use in tests

TempMailo API v2 methods, base address https://tempmailo.co/api/v2/
MethodHTTPWhat it does in a test
createPOSTA fresh address for each test or each flow
messagesGETWaiting for mail: up to 100 messages, newest first. With after set to an id, only newer ones
messageGETReading the code or link from plain or html
sourceGETThe raw email in the raw field, for checking headers
attachmentGETThe file itself, by message id and index
statusGETWhether the address is active, plus total and unread counts. Works after it expires
deletePOSTCleanup when the test ends
domainsGETDomains, lifetimes and login rules, if you choose the address yourself
usageGETHow much of today's limits is left

Every call needs the key in X-Api-Key. Mailbox methods also need the token from create in Authorization: Bearer. Parameters can go in the query string, as a form or as JSON. The addresses work like the ones on the temporary email page, except that your code creates them.

A sign-up test in Python

A small helper keeps the tests short. It creates an address, waits for a matching email, retries once after a rate limit and deletes the address at the end, even if the test fails. It checks the inbox every 5 seconds, the shortest interval the documentation recommends.

# inbox.py: a temporary inbox for one test
import os
import time

import requests

API = "https://tempmailo.co/api/v2"
KEY = {"X-Api-Key": os.environ["TEMPMAILO_KEY"]}


def call(method, path, **kw):
    """One API call. After a 429 it waits Retry-After seconds and tries once more."""
    for _ in range(2):
        resp = requests.request(method, API + path, timeout=20, **kw)
        if resp.status_code == 429:
            time.sleep(int(resp.headers.get("Retry-After", "5")))
            continue
        data = resp.json()
        if not data["ok"]:
            raise RuntimeError(f"{path}: {resp.status_code} {data['error']}")
        return data
    raise RuntimeError(f"{path}: still rate limited")


class Inbox:
    def __init__(self, lifetime=600):
        box = call("POST", "/create/", headers=KEY,
                   data={"lifetime": lifetime, "client": "signup-tests 1.0"})
        self.email = box["mailbox"]["email"]
        self.auth = {**KEY, "Authorization": "Bearer " + box["token"]}
        self.last_id = 0

    def wait_for(self, subject_part, timeout=120, every=5):
        """Waits for a new email whose subject contains subject_part, returns it in full."""
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            new = call("GET", "/messages/", headers=self.auth,
                       params={"after": self.last_id})["messages"]
            if new:
                self.last_id = max(m["id"] for m in new)
            for m in new:
                if subject_part.lower() in m["subject"].lower():
                    return call("GET", "/message/", headers=self.auth,
                                params={"id": m["id"]})["message"]
            time.sleep(every)
        raise TimeoutError(f"no email with {subject_part!r} in {timeout} s")

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        try:
            call("POST", "/delete/", headers=self.auth)
        except RuntimeError:
            pass  # already expired or deleted

With the helper in place, the test reads like the user story:

# test_signup.py
import re

import requests

from inbox import Inbox

APP = "https://staging.example.com"


def test_signup_code_confirms_the_account():
    with Inbox() as box:
        requests.post(APP + "/api/signup", timeout=20, json={
            "email": box.email, "password": "a-long-test-password"})

        mail = box.wait_for("verification code")
        code = re.search(r"\b(\d{6})\b", mail["plain"]).group(1)

        r = requests.post(APP + "/api/confirm", timeout=20, json={
            "email": box.email, "code": code})
        assert r.status_code == 200

Two details save debugging time. If your email has no text part, plain is empty, so search html instead. And match on the subject or the sender rather than taking the first message, because one address can collect several emails during a flow.

The same flow in Playwright (Node.js)

Node.js 18 and newer has fetch built in, so the helper needs no extra packages. The test fills in your real sign-up form, waits for the email and opens the confirmation link.

// signup.spec.js: Playwright, Node.js 18 or newer
import { test, expect } from '@playwright/test';

const API = 'https://tempmailo.co/api/v2';
const KEY = process.env.TEMPMAILO_KEY;

async function api(path, { method = 'GET', token, body } = {}) {
  const headers = { 'X-Api-Key': KEY };
  if (token) headers.Authorization = `Bearer ${token}`;
  if (body) headers['Content-Type'] = 'application/json';
  const res = await fetch(API + path, { method, headers, body: body && JSON.stringify(body) });
  const data = await res.json();
  if (!data.ok) throw new Error(`${path}: ${res.status} ${data.error}`);
  return data;
}

async function waitForMail(token, subject, timeoutMs = 120_000) {
  const until = Date.now() + timeoutMs;
  while (Date.now() < until) {
    const { messages } = await api('/messages/', { token });
    const hit = messages.find((m) => subject.test(m.subject));
    if (hit) return (await api(`/message/?id=${hit.id}`, { token })).message;
    await new Promise((r) => setTimeout(r, 5000));
  }
  throw new Error(`no email matching ${subject} in ${timeoutMs / 1000} s`);
}

test('a new user confirms the email address', async ({ page }) => {
  const { token, mailbox } = await api('/create/', {
    method: 'POST',
    body: { lifetime: 600, client: 'e2e 1.0' },
  });
  try {
    await page.goto('https://staging.example.com/signup');
    await page.getByLabel('Email').fill(mailbox.email);
    await page.getByLabel('Password').fill('a-long-test-password');
    await page.getByRole('button', { name: 'Create account' }).click();

    const mail = await waitForMail(token, /confirm your email/i);
    const link = mail.plain.match(/https:\/\/staging\.example\.com\/confirm\S+/)[0];
    await page.goto(link);
    await expect(page.getByText('Email confirmed')).toBeVisible();
  } finally {
    await api('/delete/', { method: 'POST', token }).catch(() => {});
  }
});

The API sends no CORS headers, so these calls run in the test process, not inside the page. That also keeps your key out of the browser.

Run it in CI

Store the key as a secret and pass it to the job as an environment variable. In GitHub Actions it looks like this:

- name: Email tests
  env:
    TEMPMAILO_KEY: ${{ secrets.TEMPMAILO_KEY }}
  run: pytest tests/email

Before a long suite, check the quota and skip with a clear message instead of failing halfway through:

# conftest.py
import os

import pytest
import requests


@pytest.fixture(scope="session", autouse=True)
def enough_addresses_left():
    usage = requests.get("https://tempmailo.co/api/v2/usage/", timeout=20,
                         headers={"X-Api-Key": os.environ["TEMPMAILO_KEY"]}).json()
    day = usage["usage"]["create_day"]
    if day["limit"] - day["used"] < 10:
        pytest.skip("fewer than 10 TempMailo addresses left today")

How many tests can wait at once

Bar chart: with 60 requests a minute, checking every 5 seconds allows 5 waiting tests, every 10 seconds 10, every 15 seconds 15, every 30 seconds 30
Our estimate from the free limit of 60 requests a minute, counting inbox checks only.

A free key allows 60 requests a minute. A test that checks the inbox every 5 seconds makes 12 requests a minute while it waits, so five such tests can wait side by side. At 10 seconds it's ten. As a rough rule, the number of tests that can wait at the same time equals your polling interval in seconds. Calls to create, message and delete count too, so leave some room. With a webhook, a test waits for the email without spending requests.

In a bigger suite the address limit runs out first: 100 new addresses a day per account. There is no hourly cap, so one run can use the whole daily quota. A few habits keep you inside it:

  • One address per flow, not per assertion. The sign-up email, the password reset and the "email changed" notice can all go to one address. Pass after with the last id you saw to wait only for the next email.
  • A lifetime that fits the flow. 600 seconds covers most checks. Use 3600 when the test has to wait, for example to see that a code expires after 15 minutes.
  • Email tests where they matter. Run them on the main branch, before a release and at night, not on every push.
  • Read the counters. Every reply to a request with a key carries X-RateLimit-Remaining and X-RateLimit-Reset for the minute count, and usage shows all counters.

Checking the email itself

A code that works isn't the whole story. The source method returns the raw email, and Python's standard library can parse its headers. Inside the with Inbox() as box block from the test above:

from email import message_from_string, policy

from inbox import call

raw = call("GET", "/source/", headers=box.auth, params={"id": mail["id"]})["raw"]
msg = message_from_string(raw, policy=policy.default)

assert msg["From"] == "Example App <noreply@app.example>"
assert msg["List-Unsubscribe"], "marketing email without List-Unsubscribe"
assert "DKIM-Signature" in msg, "the email is not DKIM-signed"

This catches a broken sender name after a template change, or a newsletter that lost its unsubscribe header. If your emails use open tracking, our guide to email tracking pixels shows what a pixel tells the sender and how readers block it.

Free limits

Limits of a free API key, checked on December 2, 2026
LimitValueWhen you reach it
New addresses100 a day, per account429 rate_limited. The count starts again at 00:00 UTC
Requests60 a minute, per account429 rate_limited. Wait for the seconds in Retry-After
API keysOne per accountA new key switches the old one off
Address lifetime10 or 60 minutesMailbox methods reply 410 expired, except status
Messages per listUp to 100, newest firstPass after to get only newer ones
Email sizeUp to 15 MB with attachmentsLarger emails don't arrive
SendingNot availableAddresses only receive

The free limits fit test suites and small projects. Higher limits are planned as a paid option, and there is no price list yet. If you need more now, tell us what you're building through the contact page. Our comparison with other inbox APIs puts these numbers next to the alternatives.

Errors and what to do

Every failed request returns JSON with "ok": false and a short code in error. A 429 also names the limit you hit:

{
  "ok": false,
  "time": 1796227300,
  "error": "rate_limited",
  "limit": {"scope": "create_day", "limit": 100, "reset": 1796256000}
}
The errors you're most likely to see in tests
Status and codeUsual causeWhat to do
401 auth_required, 401 bad_keyNo X-Api-Key header, or an old keySend the current key from your account
401 bad_tokenNo token, the address was deleted, or another account created itCreate a new address
409 login_takenThe login you asked for is in usePick another login or let the API choose one
410 expiredThe address lifetime is overCreate a new address, with 3600 for slow flows
429 rate_limitedA limit was reached, and limit says whichWait for Retry-After seconds, then retry
400 bad_...A wrong parameter, named in the codeFix that parameter
503 dberror, 503 no_domainsThe service is busy or under maintenanceRetry after a pause

If the API works but your app's email never shows up, look at the sending side first: your logs, your mail provider's activity page, a typo in the template. Our guide to a verification email that never arrives lists what goes wrong on the user's side and on the site's side.

What the API isn't for

  • Sending email. Addresses only receive. Our guide on why these addresses can't send explains why.
  • Accounts you need to keep. An address lives an hour at most. An account that may need a password reset next month needs an address you control.
  • Sign-ups on other people's sites. Test your own product. Spam, fraud and bulk sign-ups on other sites break the terms of use, and keys used for them are blocked.
  • Real personal data. Use fake users and test data. Messages are stored on our servers until the address is deleted or expires, so keep real customer data out of test inboxes.

For checks by hand, without code, see our guide to testing sign-up emails with a throwaway inbox.

FAQ

Is the TempMailo API free?

Yes, within the free limits: 100 new addresses a day and 60 requests a minute, with a free account. Higher limits are planned as a paid option.

Can I choose the address?

Yes. Pass login with 5 to 32 characters from a-z, digits, dot, underscore and hyphen, starting and ending with a letter or digit. You can also pass a domain from the domains list. If the name is taken, you get 409 login_taken. For tests, a random address is the safer default.

Will I see mail sent to that address before I created it?

No. You only get mail that arrived after you created the address, even if someone used the same name before.

Can I call the API from frontend JavaScript?

No. The API sends no CORS headers, and the key would be visible to anyone who opens the page. Call it from a server, a test runner or your app's backend.

Is there a webhook for new mail?

Yes, one per account, and a free key is enough. Every email that arrives at an address created with your key is sent to your HTTPS address as a signed POST request with JSON, usually a few seconds after it arrives. See the webhook documentation. You can still poll messages every 5 seconds or slower, and pass after so each reply holds only new mail.

Read next

All articles of the blog

We use cookies to keep your inbox open in this browser and to show ads. Cookie policy