How to Automate Email Testing: A Step-by-Step Guide Using a Temp Mail API
Automating the full lifecycle of an email—from receiving a confirmation link to verifying a password reset—is a common challenge in end-to-end (E2E) testing. Relying on real inboxes is slow and unreliable. A much better approach is to use a Temporary Email API to programmatically control your test inboxes.
This tutorial will walk you through a complete, practical workflow using Python. We will:
- Programmatically generate a new, temporary email address.
- Simulate an action by sending an email to that address.
- Automatically poll the inbox until our email arrives.
- Parse the email's content to confirm its subject and body.
We'll be using the Temp Mail API for its simple, two-endpoint design that is perfect for automation.
Step 1: Getting Your API Key
Before you start, you'll need an API key to authenticate your requests.
- Sign up for a free account at
juheapi.com
. - Navigate to your dashboard and generate a new API key.
- Copy this key, as you'll need it for the script below.
Step 2: The End-to-End Workflow
Our script will follow a logical, four-step process that you can adapt for any test suite:
- Generate Email: Call the API to create a new, random email address. The API will return the address and a unique ID for its mailbox.
- Trigger Action: In a real test, this is where your browser automation script (e.g., Selenium) would use the generated email to sign up for your service. For this self-contained demo, we will simply send an email to it ourselves.
- Poll for Message: We'll repeatedly call the API's "check inbox" endpoint using the mailbox ID. We'll keep checking every few seconds until a message appears.
- Assert and Validate: Once a message is retrieved, we'll check its contents (like the subject line) to confirm our test was successful.
Step 3: The Complete Python Script
Here is the complete, runnable Python script. Make sure you have the requests
library installed (pip install requests
).
import requests
import time
import smtplib
from email.mime.text import MIMEText
# --- Configuration ---
API_KEY = "YOUR_API_KEY" # <-- IMPORTANT: Replace with your key from hub.juheapi.com
BASE_URL = "https://hub.juheapi.com/temp_mail/v1"
# --- Configuration for sending a test email (replace with your details) ---
# Note: For real use, you might need an app-specific password for Gmail.
SENDER_EMAIL = "your_email@gmail.com"
SENDER_PASSWORD = "your_email_password"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
def generate_temp_email():
"""Generates a new temporary email address."""
print("1. Generating a new temporary email address...")
url = f"{BASE_URL}/create"
params = {'key': API_KEY}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("code") == "0" and data.get("data"):
email_info = data["data"]
print(f" - Success! Email: {email_info['email']}, ID: {email_info['id']}")
return email_info
else:
print(f" - API Error: {data.get('msg')}")
return None
except requests.exceptions.RequestException as e:
print(f" - HTTP Error: {e}")
return None
def send_test_email(recipient_email):
"""Sends a test email to the temporary address."""
print(f"\n2. Sending a test email to {recipient_email}...")
subject = "Welcome to Our Test!"
body = "This is the test email body. Confirmation successful."
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = SENDER_EMAIL
msg['To'] = recipient_email
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.send_message(msg)
print(" - Email sent successfully.")
return True
except Exception as e:
print(f" - Failed to send email: {e}")
return False
def check_inbox(mailbox_id, timeout_seconds=60):
"""Polls the inbox until an email is received or timeout occurs."""
print("\n3. Polling inbox for new mail...")
start_time = time.time()
url = f"{BASE_URL}/messages"
params = {'key': API_KEY, 'id': mailbox_id}
while time.time() - start_time < timeout_seconds:
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("code") == "0" and data.get("data"):
messages = data["data"]
if messages:
print(f" - Success! Found {len(messages)} message(s).")
return messages
print(" - Inbox is empty. Waiting 5 seconds...")
time.sleep(5)
except requests.exceptions.RequestException as e:
print(f" - HTTP Error while polling: {e}")
time.sleep(5)
print(" - Timeout reached. No email received.")
return []
def main():
"""Main execution workflow."""
# Step 1: Generate Email
email_info = generate_temp_email()
if not email_info:
return
# Step 2: Trigger Action
if not send_test_email(email_info["email"]):
return
# Step 3: Poll for Message
messages = check_inbox(email_info["id"])
# Step 4: Assert and Validate
if messages:
print("\n4. Validating received email...")
first_email = messages[0]
expected_subject = "Welcome to Our Test!"
print(f" - From: {first_email['from']}")
print(f" - Subject: {first_email['subject']}")
# This is your test assertion
if first_email['subject'] == expected_subject:
print(" - ASSERTION PASSED: Subject line is correct!")
else:
print(f" - ASSERTION FAILED: Expected subject '{expected_subject}'")
if __name__ == "__main__":
main()
Conclusion & Next Steps
You have now successfully automated a full email lifecycle: creation, reception, and programmatic reading. This exact pattern—generate, act, poll, validate—can be integrated directly into your automated test suites using frameworks like Pytest or Robot Framework. By replacing manual steps with reliable API calls, you can build a faster and more resilient testing pipeline.
What will you automate next? Dive into the full API Documentation to see options for custom domains or check out other powerful automation APIs on juheapi.com
****.