Gmail OTP API for Bots: Telegram, Discord and Scripts

A bot that hands out verification codes looks simple: someone types a command, the bot replies with an email address, and a minute later it posts the code. Behind that sit a queue, a poller, rate limits and refunds. This guide is about that design. The Python example shows the single-script version; here the same API serves many chat users at once.

Short answer: four calls do the work. POST /v1/orders rents an inbox and returns its address. POST /v1/orders/status (or GET /v1/orders/{id}) reads the code. POST /v1/orders/{id}/cancel gives up early with a 100% refund. Webhooks, set with PUT /v1/webhook, can push the code instead of you polling for it. Keep the chat handler fast, put orders in a queue, and let one loop poll every open order.

Bot architecture: handler, queue, poller

Split the bot into three parts that do not block each other:

A thread or task per order looks easier and breaks first: twenty users mean twenty loops hitting the same rate limit. One poller with a shared limiter scales much further.

Give each user their own order. Two people sharing one inbox would see each other's codes, and a refund could not be split between them.

The core loop in Python

import os, time, uuid, threading, requests

HOST = "otpgmail.net"
API = f"https://{HOST}/v1"
H = {"Authorization": f"Bearer {os.environ['OTPGMAIL_API_KEY']}", "X-Lang": "en"}
jobs, lock = {}, threading.Lock()  # orderId -> chat id; use a real store in production

def rent_for(chat_id, service, domain="gmail.com"):
    r = requests.post(f"{API}/orders", timeout=60,
                      headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                      json={"service": service, "domain": domain, "warehouse": 99})
    body = r.json()
    if not body["success"]:
        return None, body["error"]["code"]
    order = body["data"][0]
    with lock:
        jobs[order["orderId"]] = chat_id
    return order["email"], None

def poller(send):
    while True:
        with lock:
            ids = list(jobs)[:100]
        if ids:
            r = requests.post(f"{API}/orders/status", json={"ids": ids}, headers=H, timeout=30)
            for o in r.json().get("data", []):
                if o["status"] == "completed":
                    send(jobs[o["orderId"]], f"Code: {o['otp'][-1]['code']}")
                elif o["status"] == "cancelled":
                    send(jobs[o["orderId"]], "No code arrived in time, so the order was refunded.")
                else:
                    continue
                with lock:
                    jobs.pop(o["orderId"], None)
        time.sleep(4)

send is your bot library's "send message" function. X-Lang: en makes error messages English. Use requests: the default user agent of the standard-library urllib is rejected by the CDN. Retry rules for a timed-out POST /v1/orders (resend with the same Idempotency-Key, never a new one) are covered in the retries and timeouts guide.

Concurrency and limits

Timeouts and cancellation, so no balance is wasted

Every order carries codeDeadlineAt, at most 25 minutes after renting. If no code arrives by then, it cancels itself and refunds 100%, and your poller sees cancelled. You are charged only when an inbox is issued.

Give users a Cancel button anyway. When someone gives up after a couple of minutes, POST /v1/orders/{id}/cancel returns the money at once instead of holding a waiting slot. Cancelling works only before the first code; once a code is delivered, the order cannot be cancelled or refunded.

Do not build a loop that rents, cancels after twenty seconds and rents again. Some warehouses pause renting for an account that cancels many orders without a code, which shows up as RATE_LIMITED. A patient wait per order costs less.

After the first code, more codes can arrive on the same inbox when the service sends them, at no extra charge within the order period. If your users need a second code, such as a login after sign-up, keep the job open and call POST /v1/orders/{id}/next-code.

Returning the code to the user in chat

Show the address with the service name and the deadline, for example: "Use this address on GitHub. Waiting for the code until 14:32." Take that time from codeDeadlineAt instead of hard-coding a number of minutes.

Handling failures

What happens What the bot should do
NO_MAILS_AVAILABLE, OUT_OF_STOCK, ALL_WAREHOUSES_EXHAUSTED Nothing was charged. Wait error.retryAfterSec, try the other domain, or tell the user to try later
DOMAIN_UNAVAILABLE Rent again with gmail.com
RATE_LIMITED Sleep for the Retry-After seconds, then retry
INSUFFICIENT_BALANCE Stop renting and alert the bot owner; it is not the user's fault
No code before the deadline The order is refunded; offer a new attempt

Every error has error.retryable and error.retryAfterSec, so the bot can decide without a table of its own: true means wait and repeat, false means fix the cause first.

Security: key storage and logs

Follow the terms of every platform your users sign up on, and OTPGmail's acceptable use policy for automation.

Frequently asked questions

What are the API rate limits for a bot?

By default 20 requests per second and 900 per minute per API key, shared by every process using that key. Your account may have different values; the docs page shows the ones that apply. Going over returns HTTP 429 with a Retry-After header.

Does the API support webhooks?

Yes. Register one URL with PUT /v1/webhook and you receive a signed POST for order.code and order.cancelled events. Delivery is best effort, so keep a slow fallback poll with POST /v1/orders/status.

Can a bot buy Gmail accounts in bulk through the API?

Yes. Besides renting inboxes, the API can buy short-lived Gmail accounts through the /v1/mail-shop endpoints, with the same API key. The buy Gmail accounts overview explains what each account includes, and the docs page has the calls.

Should every user get their own inbox?

Yes. One order per request keeps codes private and makes refunds clean: if nobody receives a code, only that order is refunded.

Which language can I write the bot in?

Any language that can send HTTPS requests with a header. The Gmail OTP API overview lists the endpoints, and the docs page links ready-made clients.

Related guides

Get your verification code now

Sign up free. You are only charged when an inbox is issued. No code within 25 minutes — 100% refunded automatically.

Can't find the service you need? Use Add service on the rental page and we will add it if our infrastructure supports it.

Need a Gmail account you can sign in to, not just a code? See buy short-lived Gmail accounts · Refund and warranty