14 Min Read

Temp Mail for Developers & Testers: API and Automation

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.

Developer Use Cases for Temporary Email

Testing & QA

  • • Automated user registration testing
  • • Email verification flow validation
  • • Newsletter signup testing
  • • Password reset flow testing
  • • Multi-account scenario testing
  • • Cross-platform email rendering

Development & Integration

  • • CI/CD pipeline email testing
  • • Load testing email systems
  • • API endpoint testing
  • • Email template development
  • • Notification system testing
  • • Webhook validation

Why Developers Choose Temp Email APIs

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.

API Services Comparison

Temp-Mail.org API

Pricing
Free

Rate Limit

100/hour

Best Use Case

General testing, CI/CD pipelines

Key Features

REST APIJSON responses

All Features

  • REST API
  • JSON responses
  • Multiple domains
  • Real-time inbox

Pros

  • Well documented
  • Reliable uptime
  • Multiple endpoints

Cons

  • Rate limiting
  • No webhook support

1SecMail API

Pricing
Free

Rate Limit

Unlimited

Best Use Case

High-volume testing, Load testing

Key Features

Simple REST APIFast generation

All Features

  • Simple REST API
  • Fast generation
  • Bulk operations

Pros

  • No rate limits
  • Very fast
  • Simple integration

Cons

  • Basic features only
  • Limited documentation

Guerrilla Mail API

Pricing
Free/$5/month

Rate Limit

1000/day

Best Use Case

Legacy system integration

Key Features

AJAX APIEmail forwarding

All Features

  • AJAX API
  • Email forwarding
  • Custom addresses

Pros

  • Mature service
  • Forwarding options
  • Stable

Cons

  • Older API design
  • Limited modern features

Mailinator API

Pricing
$25/month+

Rate Limit

Based on plan

Best Use Case

Enterprise testing, Production systems

Key Features

Enterprise APIWebhooks

All Features

  • Enterprise API
  • Webhooks
  • Team management
  • SLA

Pros

  • Enterprise features
  • Reliable SLA
  • Webhook support

Cons

  • Paid service
  • Overkill for simple use cases

API Integration Examples

1. Basic Email Generation (JavaScript/Node.js)

// 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);
}

2. Python Testing Framework Integration

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}")

3. CI/CD Pipeline Integration (GitHub Actions)

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

Testing Automation Scenarios

User Registration Testing

Medium

Automated testing of user signup flows with email verification

Recommended Tools

SeleniumCypressPlaywright

Implementation Steps

  1. Generate temporary email via API
  2. Fill registration form with temp email
  3. Poll API for verification email
  4. Extract verification link/code
  5. Complete registration process

Email Template Testing

Easy

Validate email templates, formatting, and content delivery

Recommended Tools

API clientsEmail parsersImage validators

Implementation Steps

  1. Create temp email addresses
  2. Trigger email sending from application
  3. Fetch emails via API
  4. Parse HTML/text content
  5. Validate formatting and links

Load Testing Email Systems

Hard

Test email system performance under high loads

Recommended Tools

ArtilleryJMeterk6Custom scripts

Implementation Steps

  1. Generate multiple temp email addresses
  2. Simulate concurrent email sending
  3. Monitor delivery rates and timing
  4. Analyze performance metrics
  5. Identify bottlenecks

Development Best Practices

Error Handling & Resilience

  • • Implement retry logic with exponential backoff
  • • Handle API rate limits gracefully
  • • Have fallback temp mail services
  • • Set appropriate timeouts for email delivery
  • • Log all API interactions for debugging

Performance Optimization

  • • Cache email addresses for test sessions
  • • Use connection pooling for API calls
  • • Implement parallel email checking
  • • Minimize API calls with smart polling
  • • Clean up temp emails after tests

Test Data Management

  • • Generate unique emails per test run
  • • Store email credentials securely
  • • Document email usage patterns
  • • Implement test data cleanup procedures
  • • Use environment-specific configurations

Monitoring & Debugging

  • • Track email delivery success rates
  • • Monitor API response times
  • • Set up alerts for test failures
  • • Log email content for verification
  • • Implement health checks for APIs

Security Considerations

Security Risks & Mitigation

Potential Risks

  • • Sensitive data exposure in temp emails
  • • API key exposure in logs/code
  • • Unencrypted email transmission
  • • Test data leakage to production
  • • Third-party service dependencies

Mitigation Strategies

  • • Never use temp emails for sensitive data
  • • Store API keys in environment variables
  • • Use HTTPS for all API communications
  • • Separate test and production environments
  • • Implement service health monitoring

API Key Management

Environment Variables (.env)

TEMP_MAIL_API_KEY=your_api_key_here
TEMP_MAIL_BASE_URL=https://api.temp-mail.org
EMAIL_TIMEOUT_MS=30000

CI/CD Secrets Management

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.

Data Privacy & Compliance

  • GDPR Compliance: Ensure temp email usage complies with data protection regulations
  • Data Retention: Implement policies for automatic deletion of test data
  • Audit Trails: Log all email interactions for compliance auditing
  • Geographic Restrictions: Respect data sovereignty requirements in testing
  • Third-party Agreements: Review temp email service terms and privacy policies

Advanced Code Examples

Email Content Parser (Python)

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
    }

Multi-Service Temp Email Manager (TypeScript)

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);
  }
}

Ready to Integrate Temp Email APIs?

Start building robust email testing automation with our recommended APIs and best practices.

Table of Contents

API Quick Reference

Best Free API:

1SecMail

Most Features:

Temp-Mail.org

Enterprise:

Mailinator

Legacy:

Guerrilla Mail