Complete technical guide for developers using temporary email in testing workflows. Learn API integration, automation scripts, CI/CD pipeline integration, and best practices for email testing at scale.
Temporary email APIs provide programmatic access to disposable email addresses, enabling automated testing without polluting real inboxes or requiring complex email server setups. Perfect for CI/CD pipelines and scalable testing workflows.
Rate Limit
100/hour
Best Use Case
General testing, CI/CD pipelines
Key Features
All Features
Rate Limit
Unlimited
Best Use Case
High-volume testing, Load testing
Key Features
All Features
Rate Limit
1000/day
Best Use Case
Legacy system integration
Key Features
All Features
Rate Limit
Based on plan
Best Use Case
Enterprise testing, Production systems
Key Features
All Features
// Using Temp-Mail.org API
const axios = require('axios');
class TempMailAPI {
constructor() {
this.baseURL = 'https://api.temp-mail.org/request';
}
async generateEmail() {
try {
const response = await axios.get(`${this.baseURL}/mail/id`);
return response.data;
} catch (error) {
console.error('Email generation failed:', error);
return null;
}
}
async getInbox(emailId) {
try {
const response = await axios.get(`${this.baseURL}/source/id/${emailId}`);
return response.data;
} catch (error) {
console.error('Inbox fetch failed:', error);
return [];
}
}
async waitForEmail(emailId, timeout = 30000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const emails = await this.getInbox(emailId);
if (emails && emails.length > 0) {
return emails[0];
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
throw new Error('Email timeout');
}
}
// Usage example
async function testUserRegistration() {
const tempMail = new TempMailAPI();
const email = await tempMail.generateEmail();
console.log('Generated email:', email);
// Simulate user registration
await registerUser(email);
// Wait for verification email
const verificationEmail = await tempMail.waitForEmail(email);
console.log('Verification email received:', verificationEmail);
}
import requests
import time
import pytest
from selenium import webdriver
class TempMailHelper:
def __init__(self):
self.base_url = "https://www.1secmail.com/api/v1/"
def get_random_email(self):
response = requests.get(f"{self.base_url}?action=genRandomMailbox&count=1")
return response.json()[0] if response.json() else None
def get_messages(self, email):
login, domain = email.split('@')
response = requests.get(
f"{self.base_url}?action=getMessages&login={login}&domain={domain}"
)
return response.json()
def wait_for_message(self, email, timeout=60):
start_time = time.time()
while time.time() - start_time < timeout:
messages = self.get_messages(email)
if messages:
return messages[0]
time.sleep(2)
raise TimeoutError("No message received within timeout")
@pytest.fixture
def temp_mail():
return TempMailHelper()
@pytest.fixture
def browser():
driver = webdriver.Chrome()
yield driver
driver.quit()
def test_user_registration(temp_mail, browser):
# Generate temporary email
email = temp_mail.get_random_email()
assert email is not None
# Navigate to registration page
browser.get("https://example.com/register")
# Fill registration form
browser.find_element("name", "email").send_keys(email)
browser.find_element("name", "password").send_keys("testpass123")
browser.find_element("type", "submit").click()
# Wait for verification email
message = temp_mail.wait_for_message(email)
assert "verify" in message['subject'].lower()
print(f"Registration test passed for {email}")
name: Email Integration Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
email-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm install
- name: Run email integration tests
env:
TEMP_MAIL_API_KEY: ${{ secrets.TEMP_MAIL_API_KEY }}
TEST_BASE_URL: ${{ secrets.TEST_BASE_URL }}
run: |
npm run test:email-integration
- name: Generate test report
uses: dorny/test-reporter@v1
if: always()
with:
name: Email Integration Tests
path: 'test-results.xml'
reporter: jest-junit
Automated testing of user signup flows with email verification
Validate email templates, formatting, and content delivery
Test email system performance under high loads
TEMP_MAIL_API_KEY=your_api_key_here
TEMP_MAIL_BASE_URL=https://api.temp-mail.org
EMAIL_TIMEOUT_MS=30000
Store API keys as encrypted secrets in your CI/CD platform (GitHub Secrets, GitLab CI Variables, etc.) and inject them as environment variables during test execution.
import re
from bs4 import BeautifulSoup
from urllib.parse import urlparse
class EmailContentParser:
def __init__(self, email_content):
self.content = email_content
self.soup = BeautifulSoup(email_content, 'html.parser')
def extract_verification_code(self):
# Common OTP patterns
patterns = [
r'\b\d{4,8}\b', # 4-8 digit codes
r'verification code[:\s]+([\d\w]{4,8})',
r'your code[:\s]+([\d\w]{4,8})',
r'confirm[:\s]+([\d\w]{4,8})'
]
for pattern in patterns:
matches = re.findall(pattern, self.content, re.IGNORECASE)
if matches:
return matches[0]
return None
def extract_verification_links(self):
links = []
for link in self.soup.find_all('a', href=True):
href = link['href']
if any(keyword in href.lower() for keyword in
['verify', 'confirm', 'activate', 'validation']):
links.append({
'url': href,
'text': link.get_text().strip()
})
return links
def extract_sender_info(self):
# Extract from common email headers
sender_patterns = [
r'from[:\s]+([\w\.-]+@[\w\.-]+)',
r'sender[:\s]+([\w\.-]+@[\w\.-]+)'
]
for pattern in sender_patterns:
match = re.search(pattern, self.content, re.IGNORECASE)
if match:
return match.group(1)
return None
# Usage example
def process_verification_email(email_content):
parser = EmailContentParser(email_content)
code = parser.extract_verification_code()
links = parser.extract_verification_links()
sender = parser.extract_sender_info()
return {
'verification_code': code,
'verification_links': links,
'sender': sender
}
interface TempEmailService {
generateEmail(): Promise<string>;
getMessages(email: string): Promise<Email[]>;
deleteEmail(email: string): Promise<boolean>;
}
interface Email {
id: string;
from: string;
subject: string;
content: string;
timestamp: Date;
}
class TempMailManager {
private services: TempEmailService[] = [];
private currentServiceIndex = 0;
constructor() {
this.services = [
new TempMailOrgService(),
new OneSecMailService(),
new GuerrillaMailService()
];
}
async generateEmailWithFallback(): Promise<string> {
for (let i = 0; i < this.services.length; i++) {
try {
const email = await this.services[this.currentServiceIndex].generateEmail();
if (email) return email;
} catch (error) {
console.warn(`Service ${this.currentServiceIndex} failed:`, error);
}
this.currentServiceIndex = (this.currentServiceIndex + 1) % this.services.length;
}
throw new Error('All temp email services failed');
}
async waitForEmailWithPattern(
email: string,
pattern: RegExp,
timeoutMs: number = 30000
): Promise<Email | null> {
const startTime = Date.now();
while (Date.now() - startTime < timeoutMs) {
try {
const messages = await this.getMessagesForEmail(email);
for (const message of messages) {
if (pattern.test(message.subject) || pattern.test(message.content)) {
return message;
}
}
await this.sleep(2000);
} catch (error) {
console.warn('Error checking messages:', error);
await this.sleep(5000);
}
}
return null;
}
private async getMessagesForEmail(email: string): Promise<Email[]> {
const serviceIndex = this.findServiceForEmail(email);
return this.services[serviceIndex].getMessages(email);
}
private findServiceForEmail(email: string): number {
// Logic to determine which service generated the email
// Based on email domain or stored mapping
return 0; // Simplified
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage in test
async function testWithTempEmail() {
const manager = new TempMailManager();
try {
const email = await manager.generateEmailWithFallback();
console.log('Generated email:', email);
// Trigger registration
await triggerUserRegistration(email);
// Wait for verification email
const verificationPattern = /verify|confirm|activate/i;
const message = await manager.waitForEmailWithPattern(email, verificationPattern);
if (message) {
console.log('Verification email received:', message.subject);
// Process verification
} else {
throw new Error('Verification email not received');
}
} catch (error) {
console.error('Test failed:', error);
}
}
Start building robust email testing automation with our recommended APIs and best practices.
Best Free API:
1SecMail
Most Features:
Temp-Mail.org
Enterprise:
Mailinator
Legacy:
Guerrilla Mail