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.tmQuick 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.
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:
Retrieve all available email domains
// 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:
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) |
// 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:
Authenticate and receive JWT token
Request Body Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
address |
string | Required | Your email address |
password |
string | Required | Your password |
// 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!');
Authorization header for all protected API requests.
Fetch Inbox Messages
Retrieve messages from your temporary email inbox using the authentication token.
🔹 Get All Messages
Retrieve all messages in your inbox
Headers:
| Header | Value | Description |
|---|---|---|
Authorization |
Bearer {token} | Your JWT authentication token |
Accept |
application/json | Response format |
// 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
Retrieve a specific message by ID
// 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 a specific message from your inbox
// 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:
// 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);
})();
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 |
429 Too Many Requests response. Implement exponential backoff and respect
rate limits.
🔹 Best Practices
- Use Polling Wisely: Poll for messages at reasonable intervals (5-10 seconds minimum)
- Cache Tokens: Store JWT tokens and reuse them until expiration
- Handle Errors: Implement proper error handling for network failures and API errors
- Implement Backoff: Use exponential backoff when rate limits are hit
- Clean Up: Delete messages and accounts when no longer needed
- Use HTTPS: Always use HTTPS for API requests to ensure security
- Validate Input: Validate email addresses and passwords before sending requests
🔹 Error Handling Example
// 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
- 🔒 Never Share Tokens: Keep your JWT tokens private and never expose them in client-side code
- 🔐 Use HTTPS Only: Always make API requests over HTTPS to prevent token interception
- ⏰ Token Expiration: Tokens expire after a certain period. Implement token refresh logic
- 🗑️ Clean Up Data: Delete temporary accounts and messages when no longer needed
- 🚫 Don't Store Sensitive Data: Never use temporary emails for sensitive or important communications
- 📊 Monitor Usage: Track your API usage to avoid hitting rate limits
- 🔄 Rotate Credentials: Regularly create new accounts instead of reusing old ones
Additional Resources
🔹 Code Examples Repository
Find more code examples in different programming languages:
- Python: Using requests library
- Node.js: Using axios or fetch
- PHP: Using cURL
- Ruby: Using HTTParty
- Go: Using net/http
Need Help?
If you have questions about our API or need assistance with integration:
- 📧 Email: api@tempmail.com
- 📝 Support: Contact Form
- 📚 Documentation: Mail.tm Docs
- 🐛 Report Issues: Report a Bug