temp-disposable-email
Version:
Generating Temporary email address for testing, retrieving email from the temporary email address
184 lines • 7.16 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAccount = exports.createAccount = exports.deleteMessage = exports.getMessageAttachments = exports.getMessagesContent = exports.getMessages = exports.getDomains = exports.getAuthHeaders = exports.authenticate = void 0;
const axios_1 = __importDefault(require("axios"));
const _1 = require(".");
// Store token and credentials globally
let token = null;
let email;
let password;
const apiClient = axios_1.default.create({
baseURL: 'https://api.mail.tm',
headers: { accept: 'application/json' },
});
// Function to authenticate and get a new token
const authenticate = async (_email, _password) => {
email = _email;
password = _password;
const response = await apiClient.post('/token', { address: email, password });
token = response.data.token;
};
exports.authenticate = authenticate;
// Function to get auth headers
const getAuthHeaders = () => {
if (!token) {
throw new Error('Authentication required. Token not found.');
}
return {
accept: 'application/json',
Authorization: `Bearer ${token}`,
};
};
exports.getAuthHeaders = getAuthHeaders;
// Axios interceptor to handle 401 errors and refresh token
apiClient.interceptors.response.use((response) => response, async (error) => {
if (error.response?.status === 401 && token) {
try {
await (0, exports.authenticate)(email, password); // Get a new token
error.config.headers = (0, exports.getAuthHeaders)(); // Update headers with new token
return apiClient.request(error.config); // Retry request
}
catch (_authError) {
throw new Error('Authentication failed. Please check credentials.');
}
}
return Promise.reject(error);
});
// Function to fetch domains
const getDomains = async () => {
try {
const { data } = await apiClient.get('/domains', {
headers: { accept: 'application/json' },
});
return data;
}
catch (_error) {
throw new Error('Failed to fetch domains. Please try again later.');
}
};
exports.getDomains = getDomains;
// Function to fetch messages with retry logic and timeout
const getMessages = async (maxRetries = 5, retryDelay = 10000) => {
let attempt = 0;
while (attempt < maxRetries) {
try {
const { data } = await apiClient.get('/messages?page=1', {
headers: (0, exports.getAuthHeaders)(),
});
return data;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}
catch (error) {
attempt++;
if (error.response?.status === 429 && attempt < maxRetries) {
console.warn(`Rate limited. Retrying in ${retryDelay / 1000}s... (Attempt ${attempt}/${maxRetries})`);
await (0, _1.delay)(retryDelay);
}
else if (attempt >= maxRetries) {
throw new Error(`Failed to fetch messages after ${maxRetries} attempts. Please try again later.`);
}
else {
throw new Error('Failed to fetch messages. Please try again later.');
}
}
}
throw new Error('Failed to fetch messages after maximum retries.');
};
exports.getMessages = getMessages;
// Function to fetch message content
const getMessagesContent = async (messageId) => {
try {
const { data } = await apiClient.get(`/messages/${messageId}`, {
headers: (0, exports.getAuthHeaders)(),
});
return data;
}
catch (_error) {
throw new Error('Failed to fetch message content. Please try again later.');
}
};
exports.getMessagesContent = getMessagesContent;
// Function to fetch message attachments
const getMessageAttachments = async (messageId, attachmentsId) => {
try {
const { data } = await apiClient.get(`/messages/${messageId}/attachment/${attachmentsId}`, {
responseType: 'arraybuffer',
headers: (0, exports.getAuthHeaders)(),
});
return data;
}
catch (_error) {
throw new Error('Failed to fetch message attachment. Please try again later.');
}
};
exports.getMessageAttachments = getMessageAttachments;
// Function to delete a message
const deleteMessage = async (messageId) => {
try {
const { status } = await apiClient.delete(`/messages/${messageId}`, {
headers: (0, exports.getAuthHeaders)(),
});
return status;
}
catch (_error) {
console.warn(`Error deleting message for ID ${messageId}`);
return 0;
}
};
exports.deleteMessage = deleteMessage;
// Function to create an email account
const createAccount = async (payload, domain, // Domain to use for fallback email generation
maxRetries = 10, delayMs = 6000, infiniteRetry = false // Optional: Keep retrying forever
) => {
let attempt = 1;
while (attempt <= maxRetries || infiniteRetry) {
try {
const { data } = await apiClient.post('/accounts', payload, {
headers: { accept: 'application/json' },
});
return data;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}
catch (error) {
const status = error.response?.status;
const isNetworkError = error.code === 'ECONNABORTED' || !error.response;
if (status === 409 || status === 422) {
// Use provided domain or extract from original address
const domainToUse = domain || payload.address.split('@')[1];
payload.address = `${Date.now()}-${Math.floor(Math.random() * 100000)}@${domainToUse}`;
console.warn(`Address already exists or invalid. Retrying with: ${payload.address}`);
}
else if (status === 429) {
console.warn(`Rate limited. Waiting 30 seconds before retry... (Attempt ${attempt}/${maxRetries})`);
await (0, _1.delay)(30000);
}
else if (status === 500 || isNetworkError) {
const waitTime = Math.min(30000, delayMs * attempt);
console.warn(`Server error or network issue. Waiting ${waitTime / 1000}s... (Attempt ${attempt}/${maxRetries})`);
await (0, _1.delay)(waitTime);
}
else {
throw error;
}
attempt++;
}
}
throw new Error('🚨 Max retries reached. Account creation failed.');
};
exports.createAccount = createAccount;
// Function to delete an account
const deleteAccount = async (accountId) => {
try {
await apiClient.delete(`/accounts/${accountId}`, {
headers: (0, exports.getAuthHeaders)(),
});
}
catch (_error) {
console.warn(`Failed to delete account ${accountId}, ignoring error.`);
}
};
exports.deleteAccount = deleteAccount;
//# sourceMappingURL=api.js.map