Automating OTP Verification with TmpMail API & Python
A practical tutorial on using the TmpMail API to automate verification code extraction for testing and development workflows.
The Problem
You're building an app that sends verification emails. Testing manually is painful:
1. Enter your email
Let's automate this with TmpMail.
Prerequisites
pip install requestsBasic Usage
import requests
import timeBASE_URL = "https://get-a-temp-email.xyz"
def create_temp_email():
"""Create a new temporary email inbox."""
response = requests.post(f"{BASE_URL}/api/inbox")
data = response.json()
if data["success"]:
return data["data"]
raise Exception(f"Failed to create inbox: {data}")
def get_emails(token):
"""Get all emails for an inbox."""
response = requests.get(f"{BASE_URL}/api/inbox/{token}/emails")
data = response.json()
if data["success"]:
return data["data"]
return []
def wait_for_code(token, timeout=300, poll_interval=5):
"""Wait for a verification code to arrive."""
start_time = time.time()
while time.time() - start_time < timeout:
emails = get_emails(token)
for email in emails:
codes = email.get("extracted", {}).get("codes", [])
if codes:
return codes[0]
time.sleep(poll_interval)
raise TimeoutError("No verification code received")
# Example usage
if __name__ == "__main__":
# Create temporary inbox
inbox = create_temp_email()
print(f"📧 Your temp email: {inbox['email']}")
print(f"🔑 Token: {inbox['token']}")
# Use this email to sign up for something...
print("\nWaiting for verification code...")
# Wait for and extract the code
code = wait_for_code(inbox["token"])
print(f"✅ Verification code: {code}")
Integration with Selenium
Here's a real-world example—automating signup on a website:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ECdef automated_signup(signup_url):
# Create temp email
inbox = create_temp_email()
temp_email = inbox["email"]
token = inbox["token"]
# Setup browser
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
try:
# Navigate to signup
driver.get(signup_url)
# Fill signup form
email_input = wait.until(
EC.presence_of_element_located((By.NAME, "email"))
)
email_input.send_keys(temp_email)
# Submit form
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# Wait for verification code
print(f"Waiting for code at {temp_email}...")
code = wait_for_code(token)
print(f"Got code: {code}")
# Enter verification code
code_input = wait.until(
EC.presence_of_element_located((By.NAME, "verification_code"))
)
code_input.send_keys(code)
# Complete verification
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
print("✅ Signup complete!")
finally:
driver.quit()
Pytest Integration
For test suites:
import pytestclass TestUserSignup:
@pytest.fixture
def temp_inbox(self):
"""Create a fresh inbox for each test."""
inbox = create_temp_email()
yield inbox
# Inbox auto-expires after 24h, no cleanup needed
def test_signup_sends_verification_email(self, temp_inbox, api_client):
# Trigger signup
response = api_client.post("/signup", json={
"email": temp_inbox["email"],
"password": "test123"
})
assert response.status_code == 200
# Verify email was sent
time.sleep(2) # Give it a moment
emails = get_emails(temp_inbox["token"])
assert len(emails) == 1
assert "verification" in emails[0]["subject"].lower()
def test_verification_code_works(self, temp_inbox, api_client):
# Sign up
api_client.post("/signup", json={
"email": temp_inbox["email"],
"password": "test123"
})
# Get the code
code = wait_for_code(temp_inbox["token"], timeout=30)
# Verify
response = api_client.post("/verify", json={
"email": temp_inbox["email"],
"code": code
})
assert response.status_code == 200
assert response.json()["verified"] == True
CI/CD Integration
For GitHub Actions:
name: E2E Testson: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests with temp email
run: pytest tests/e2e/ -v
env:
TMPMAIL_API: https://get-a-temp-email.xyz
Error Handling
Production-ready code should handle failures:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retrydef create_session():
"""Create a session with retries."""
session = requests.Session()
retries = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504]
)
session.mount("https://", HTTPAdapter(max_retries=retries))
return session
def safe_wait_for_code(token, timeout=300):
"""Wait for code with proper error handling."""
session = create_session()
start_time = time.time()
last_error = None
while time.time() - start_time < timeout:
try:
response = session.get(
f"{BASE_URL}/api/inbox/{token}/emails",
timeout=10
)
response.raise_for_status()
emails = response.json().get("data", [])
for email in emails:
codes = email.get("extracted", {}).get("codes", [])
if codes:
return codes[0]
except requests.RequestException as e:
last_error = e
print(f"Request failed: {e}, retrying...")
time.sleep(5)
if last_error:
raise last_error
raise TimeoutError("No verification code received")
Rate Limiting
Be mindful of API limits:
- 10 inbox creations/minute per IP
- 60 email checks/minute per token
For bulk testing, add delays:
import timedef batch_test(count=100):
# Respect rate limits if (i + 1) % 10 == 0: print(f"Completed {i + 1} tests, cooling down...") time.sleep(60)
Conclusion
TmpMail's API makes email verification testing trivial. No more manual email checking, no more test accounts with cluttered inboxes.
Check out our API documentation for complete reference.
---
*Questions? admin@get-a-temp-email.xyz*
Ready to try TmpMail?
Get a disposable email address in seconds. No signup required.
Create Temp Email