JavaScript and TypeScript examples for Mailoverse. Learn to retrieve emails using fetch, axios, and implement polling patterns for automated email testing in Node.js.

JavaScript / TypeScript

Examples for Node.js, Deno, Bun, and browser environments using native fetch and popular libraries.

Using fetch

const MAILOVERSE_DOMAIN = process.env.MAILOVERSE_DOMAIN;
const MAILOVERSE_API_KEY = process.env.MAILOVERSE_API_KEY;

async function getEmail(address: string) {
  const response = await fetch(
    `https://api.mailoverse.com/email?address=${encodeURIComponent(address)}`,
    {
      headers: {
        'Authorization': `Bearer ${MAILOVERSE_API_KEY}`,
      },
    }
  );

  if (!response.ok) {
    throw new Error(`Failed to fetch email: ${response.status}`);
  }

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

// Usage
const email = await getEmail(`test@${MAILOVERSE_DOMAIN}`);
if (email) {
  console.log('Subject:', email.subject);
  console.log('Links:', email.parsedHtml?.links);
}

With Polling

Email delivery isn't instant. Here's a helper function that polls until an email arrives:

async function waitForEmail(
  address: string,
  options: { timeout?: number; interval?: number } = {}
) {
  const { timeout = 30000, interval = 1000 } = options;
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    const response = await fetch(
      `https://api.mailoverse.com/email?address=${encodeURIComponent(address)}`,
      {
        headers: {
          'Authorization': `Bearer ${process.env.MAILOVERSE_API_KEY}`,
        },
      }
    );

    const data = await response.json();

    if (data.email) {
      return data.email;
    }

    await new Promise(resolve => setTimeout(resolve, interval));
  }

  throw new Error(`Timeout waiting for email to ${address}`);
}

// Usage
const email = await waitForEmail('test@yoursubdomain.mailoverse.com');
console.log('Received email:', email.subject);

Using Axios

import axios from 'axios';

const mailoverse = axios.create({
  baseURL: 'https://api.mailoverse.com',
  headers: {
    'Authorization': `Bearer ${process.env.MAILOVERSE_API_KEY}`,
  },
});

async function getEmail(address: string) {
  const { data } = await mailoverse.get('/email', {
    params: { address },
  });
  return data.email;
}

// Usage
const email = await getEmail('test@yoursubdomain.mailoverse.com');

TypeScript Types

TypeScript interface for the email response:

interface MailoverseEmail {
  id: string;
  from: string[];
  to: string[];
  subject?: string;
  body?: string;
  htmlBody?: string;
  parsedHtml?: {
    links: Array<{ href: string; text: string }>;
    images: string[];
    body: string;
  };
  parsedText?: {
    links: Array<{ href: string; text: string }>;
    images: string[];
    body: string;
  };
  receivedAt: string;
}

interface MailoverseResponse {
  email: MailoverseEmail | null;
}

See Also