API Documentation

Integrate temporary email functionality into your applications using our powerful Mail.tm API integration. Create disposable emails, fetch messages, and automate email workflows.

🔗 Base URL: https://api.mail.tm

Quick Start Guide

Get started with our temporary email API in just a few steps. Our service is powered by Mail.tm, a robust and privacy-focused temporary email API.

📚 Official Documentation: For complete API reference, visit https://docs.mail.tm/

Authentication

The Mail.tm API uses JWT (JSON Web Token) authentication. You need to create an account and obtain a token to access protected endpoints.

🔹 Step 1: Get Available Domains

First, fetch the list of available domains for creating temporary email addresses:

GET /domains

Retrieve all available email domains

JavaScript (Fetch API)
// Get available domains
fetch('https://api.mail.tm/domains', {
  method: 'GET',
  headers: {
    'Accept': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log('Available domains:', data);
  // Example response: {"hydra:member": [{"id": "...", "domain": "example.com"}]}
})
.catch(error => console.error('Error:', error));

🔹 Step 2: Create an Account

Create a temporary email account using one of the available domains:

POST /accounts

Create a new temporary email account

Request Body Parameters:

Parameter Type Required Description
address string Required Email address (e.g., user@domain.com)
password string Required Password (min 8 characters)
JavaScript (Fetch API)
// Create temporary email account
const createAccount = async () => {
  const domain = 'example.com'; // Use domain from Step 1
  const username = 'user' + Math.random().toString(36).substring(7);
  const email = `${username}@${domain}`;
  const password = 'SecurePass123!';

  const response = await fetch('https://api.mail.tm/accounts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      address: email,
      password: password
    })
  });

  const data = await response.json();
  console.log('Account created:', data);
  return { email, password };
};

createAccount();

🔹 Step 3: Get Authentication Token

Obtain a JWT token by logging in with your created account:

POST /token

Authenticate and receive JWT token

Request Body Parameters:

Parameter Type Required Description
address string Required Your email address
password string Required Your password
JavaScript (Fetch API)
// Get authentication token
const getToken = async (email, password) => {
  const response = await fetch('https://api.mail.tm/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      address: email,
      password: password
    })
  });

  const data = await response.json();
  console.log('Token received:', data.token);
  
  // Store token for future requests
  localStorage.setItem('api_token', data.token);
  return data.token;
};

// Usage
getToken('user@example.com', 'SecurePass123!');
✅ Authentication Complete! You now have a JWT token. Include this token in the Authorization header for all protected API requests.

Fetch Inbox Messages

Retrieve messages from your temporary email inbox using the authentication token.

🔹 Get All Messages

GET /messages

Retrieve all messages in your inbox

Headers:

Header Value Description
Authorization Bearer {token} Your JWT authentication token
Accept application/json Response format
JavaScript (Fetch API)
// Fetch all messages
const getMessages = async () => {
  const token = localStorage.getItem('api_token');
  
  const response = await fetch('https://api.mail.tm/messages', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    }
  });

  const data = await response.json();
  console.log('Messages:', data['hydra:member']);
  
  // Display messages
  data['hydra:member'].forEach(message => {
    console.log(`From: ${message.from.address}`);
    console.log(`Subject: ${message.subject}`);
    console.log(`Date: ${message.createdAt}`);
  });
  
  return data['hydra:member'];
};

getMessages();

🔹 Get Single Message

GET /messages/{id}

Retrieve a specific message by ID

JavaScript (Fetch API)
// Get single message with full content
const getMessage = async (messageId) => {
  const token = localStorage.getItem('api_token');
  
  const response = await fetch(`https://api.mail.tm/messages/${messageId}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    }
  });

  const message = await response.json();
  console.log('Message details:', message);
  console.log('HTML Content:', message.html);
  console.log('Text Content:', message.text);
  
  return message;
};

// Usage
getMessage('message-id-here');

🔹 Delete Message

DELETE /messages/{id}

Delete a specific message from your inbox

JavaScript (Fetch API)
// Delete a message
const deleteMessage = async (messageId) => {
  const token = localStorage.getItem('api_token');
  
  const response = await fetch(`https://api.mail.tm/messages/${messageId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  if (response.status === 204) {
    console.log('Message deleted successfully');
  }
};

deleteMessage('message-id-here');

Complete Integration Example

Here's a complete example showing how to create a temporary email account, fetch messages, and handle the entire workflow:

JavaScript (Complete Example)
// Complete Temporary Email API Integration
class TempMailAPI {
  constructor() {
    this.baseURL = 'https://api.mail.tm';
    this.token = null;
    this.email = null;
  }

  // Step 1: Get available domains
  async getDomains() {
    const response = await fetch(`${this.baseURL}/domains`);
    const data = await response.json();
    return data['hydra:member'];
  }

  // Step 2: Create account
  async createAccount() {
    const domains = await this.getDomains();
    const domain = domains[0].domain;
    const username = 'user' + Math.random().toString(36).substring(7);
    this.email = `${username}@${domain}`;
    const password = 'TempPass' + Math.random().toString(36).substring(7) + '!';

    const response = await fetch(`${this.baseURL}/accounts`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        address: this.email,
        password: password
      })
    });

    if (!response.ok) {
      throw new Error('Failed to create account');
    }

    // Step 3: Get token
    await this.getToken(this.email, password);
    return this.email;
  }

  // Step 3: Authenticate and get token
  async getToken(email, password) {
    const response = await fetch(`${this.baseURL}/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        address: email,
        password: password
      })
    });

    const data = await response.json();
    this.token = data.token;
    return this.token;
  }

  // Step 4: Fetch messages
  async getMessages() {
    const response = await fetch(`${this.baseURL}/messages`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Accept': 'application/json'
      }
    });

    const data = await response.json();
    return data['hydra:member'];
  }

  // Get single message
  async getMessage(messageId) {
    const response = await fetch(`${this.baseURL}/messages/${messageId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Accept': 'application/json'
      }
    });

    return await response.json();
  }

  // Delete message
  async deleteMessage(messageId) {
    await fetch(`${this.baseURL}/messages/${messageId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    });
  }

  // Poll for new messages
  async pollMessages(callback, interval = 5000) {
    const poll = async () => {
      const messages = await this.getMessages();
      callback(messages);
    };

    poll(); // Initial fetch
    return setInterval(poll, interval);
  }
}

// Usage Example
(async () => {
  const tempMail = new TempMailAPI();
  
  // Create temporary email
  const email = await tempMail.createAccount();
  console.log('Temporary email created:', email);
  
  // Poll for messages every 5 seconds
  const pollInterval = await tempMail.pollMessages((messages) => {
    console.log(`Received ${messages.length} messages`);
    messages.forEach(msg => {
      console.log(`- ${msg.subject} from ${msg.from.address}`);
    });
  }, 5000);
  
  // Stop polling after 60 seconds
  setTimeout(() => {
    clearInterval(pollInterval);
    console.log('Stopped polling');
  }, 60000);
})();
🎉 Ready to Use! This complete example handles account creation, authentication, and message polling. Customize it for your specific needs.

Rate Limits & Best Practices

🔹 API Rate Limits

To ensure fair usage and prevent abuse, the following rate limits apply:

Endpoint Limit Window
Account Creation 5 requests Per hour
Token Generation 10 requests Per hour
Message Fetching 100 requests Per hour
Domain Listing 50 requests Per hour
Overall API 200 requests Per hour
⚠️ Rate Limit Exceeded: If you exceed these limits, you'll receive a 429 Too Many Requests response. Implement exponential backoff and respect rate limits.

🔹 Best Practices

🔹 Error Handling Example

JavaScript (Error Handling)
// Robust error handling
async function apiRequest(url, options) {
  try {
    const response = await fetch(url, options);
    
    // Handle rate limiting
    if (response.status === 429) {
      console.warn('Rate limit exceeded. Waiting before retry...');
      await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute
      return apiRequest(url, options); // Retry
    }
    
    // Handle authentication errors
    if (response.status === 401) {
      console.error('Authentication failed. Token may be expired.');
      // Re-authenticate here
      throw new Error('Authentication required');
    }
    
    // Handle not found
    if (response.status === 404) {
      throw new Error('Resource not found');
    }
    
    // Handle server errors
    if (response.status >= 500) {
      throw new Error('Server error. Please try again later.');
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
}

Security & Privacy Tips

🔐 Privacy First: Our temporary email service is designed for privacy. All emails are automatically deleted after expiration, and we don't track or store personal information.

Additional Resources

🔹 Code Examples Repository

Find more code examples in different programming languages:

Need Help?

If you have questions about our API or need assistance with integration: