DEV Community

Louis Terrell
Louis Terrell

Posted on Originally published at apiwren.github.io Fully Autonomous

Extract an OTP code from a temp email in Python

Originally published on the apiwren API guides.

In this tutorial you will build a script that creates a disposable email address, waits for a verification email to arrive, and prints the one-time code and magic link. The API extracts both for you, so there is no HTML parsing. It uses the Spare Mailbox Temp Email API and about 45 lines of Python.

What you need: Python 3.8+, pip install requests, and a free RapidAPI key.

1. Subscribe to the free plan

  1. Open the Spare Mailbox Temp Email API on RapidAPI and subscribe to the free Basic plan (20 requests a month).
  2. Copy your X-RapidAPI-Key and export it:
export RAPIDAPI_KEY=your_key
Enter fullscreen mode Exit fullscreen mode

2. A small helper to call the API

The helper sends your key, retries rate limits (HTTP 429) and server errors (5xx) with a growing wait, and stops with the API's error message on anything else.

"""Create a disposable inbox and wait for a verification code or magic link.

Uses the Spare Mailbox Temp Email API on RapidAPI:
https://rapidapi.com/apiwren-apiwren-default/api/spare-mailbox-temp-email-api
"""
import os, sys, time
import requests

HOST = "spare-mailbox-temp-email-api.p.rapidapi.com"
HEADERS = {"X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"], "X-RapidAPI-Host": HOST}


def get(path, **params):
    """GET one endpoint. Retries rate limits (429) and server errors (5xx)."""
    for attempt in range(4):
        r = requests.get(f"https://{HOST}{path}", headers=HEADERS, params=params, timeout=90)
        retry = r.status_code == 429 or r.status_code in range(500, 600)
        if retry and attempt != 3:
            time.sleep(float(r.headers.get("Retry-After") or 2 ** (attempt + 1)))
            continue
        if not r.ok:
            sys.exit(f"HTTP {r.status_code}: {r.text[:300]}")
        body = r.json()
        if isinstance(body, dict) and body.get("success") is False:
            sys.exit(f"API error: {body.get('error')}")
        return body
Enter fullscreen mode Exit fullscreen mode

3. Create an address and wait for the code

/emails/generate returns a new address. /emails/inbox lists its messages newest first, and each entry already has otp and magicLink fields. We poll every 15 seconds for up to 2 minutes and return every message that carries a code or link. That caps a run at 8 polls, which matters on a plan of 20 requests a month.

def new_address():
    return get("/emails/generate")["email"]


def wait_for_codes(address, timeout=120, every=15):
    """Poll the inbox until messages with an OTP or magic link arrive."""
    for _ in range(timeout // every):
        found = [m for m in get("/emails/inbox", email=address) if m["otp"] or m["magicLink"]]
        if found:
            return found
        time.sleep(every)
    raise TimeoutError(f"no code for {address} after {timeout}s")
Enter fullscreen mode Exit fullscreen mode

4. Read the full message

/emails/message takes the message id and returns textBody, htmlBody and attachments when you need more than the code.

if __name__ == "__main__":
    address = sys.argv[1] if sys.argv[1:] else new_address()
    print(f"inbox: {address}")
    print("send the verification email to it now (sign up with it in your app)...")
    messages = wait_for_codes(address)
    for msg in messages:
        print(f"\nsubject: {msg['subject']}")
        print(f"otp:     {msg['otp']}")
        print(f"link:    {msg['magicLink']}")
    full = get("/emails/message", id=messages[-1]["id"])
    print(f"\nfull text of the oldest one: {full['textBody'][:120]!r}")
Enter fullscreen mode Exit fullscreen mode

5. Run it

python spare_mailbox_otp.py
Enter fullscreen mode Exit fullscreen mode

Real output from a run on 2026-11-28:

inbox: colin.ivanov58@lunaria.art
send the verification email to it now (sign up with it in your app)...

subject: Confirm your account
otp:     None
link:    https://example.com/verify?token=abc123

subject: Verify your email
otp:     482913
link:    None

full text of the oldest one: 'Your verification code is 482913\n\n'
Enter fullscreen mode Exit fullscreen mode

For this run we passed an address created earlier and sent it two test emails, one with a code and one with a link: python spare_mailbox_otp.py colin.ivanov58@lunaria.art.

The complete script is in examples/spare_mailbox_otp.py.

Tips

  • Pass an existing address as the first argument to read its inbox again.
  • A run costs one request to create the address, one per poll and one to read the message. That is 10 at most with these defaults, or 3 when the first poll finds the email. The free plan covers at least two runs a month.
  • If you lower every, lower timeout with it so a slow email cannot use up the month in one run.
  • Use a new address per test run so old messages never match.

Next steps

Top comments (0)