Docs / SDK Patterns

Guide 9 of 9

Common SDK Patterns

Real-world code patterns for email testing. Copy, adapt, and use in your test suite. All examples support TypeScript, JavaScript, and curl.


1

OTP Extraction (Auto-Detect)

The SDK recognizes common OTP formats automatically. No regex needed for standard patterns.

const otp = await mf.emails.extractOtp(INBOX_ID, {
  from: '[email protected]',
  wait_timeout_ms: 15_000,
});
// → "482910"
Auto-detected formats: 6-digit codes, "Your code is X", "verification code: X", "PIN: X", and similar patterns. Library updated regularly with new formats.
2

OTP Extraction (Custom Regex)

When auto-detect doesn't work, pass a custom regex pattern. The SDK returns the first capturing group.

const otp = await mf.emails.extractOtp(INBOX_ID, {
  pattern: 'Activation PIN[:\s]+([A-Z0-9]{8})',
  wait_timeout_ms: 15_000,
});
// → "X7K2P9QR"
3

OTP with Alias Isolation

Isolate each test run with an ephemeral alias. Perfect for CI/CD where multiple tests run in parallel.

// Create ephemeral alias for this test run
const alias = await mf.inboxes.createAlias(INBOX_ID, {
  tag: `run-${Date.now()}`,
  ttl_hours: 1,
  on_expire: 'delete',
});

// Send email to the alias address from your app:
// [email protected]

// Extract OTP scoped to this alias only
const otp = await mf.emails.extractOtp(INBOX_ID, {
  alias_tag: alias.tag,
  wait_timeout_ms: 20_000,
});
Why aliases? Each test creates a unique alias tag. The inbox address stays the same; only the tag changes. When the TTL expires (1 hour), emails for that alias are auto-deleted. No manual cleanup.
4

Extract URL by Button Text

Find action links in email HTML by matching the visible button text. Most common pattern for magic links and password resets.

const url = await mf.emails.extractUrl(INBOX_ID, {
  button_text: 'Verify Email',
  wait_timeout_ms: 15_000,
});
// → "https://app.acme.com/verify?token=abc"
Match behavior: Substring, case-insensitive. "Verify Email" matches "VERIFY EMAIL", "verify email", "Verify email Now", etc.
5

Extract Multiple URLs (Approval Flows)

Use Promise.all to extract different action links (Approve / Reject) from the same email.

// Extract two different buttons from the same email
const [approveUrl, rejectUrl] = await Promise.all([
  mf.emails.extractUrl(INBOX_ID, {
    subject: 'Action Required',
    button_text: 'Approve',
    wait_timeout_ms: 15_000,
  }),
  mf.emails.extractUrl(INBOX_ID, {
    subject: 'Action Required',
    button_text: 'Reject',
    wait_timeout_ms: 15_000,
  }),
]);
7

Playwright: Isolated Alias per Test

Create an ephemeral alias before the test, send to that alias, and extract from it. Perfect for parallel CI runs.

test('verify email — isolated per test run', async ({ page }) => {
  // Create an ephemeral alias; the address is ci+run-<ts>@qa.acme.mailfork.dev
  const alias = await mfPlayer.sdk.inboxes.createAlias(INBOX_ID, {
    tag: `run-${Date.now()}`,
    ttl_hours: 1,
    on_expire: 'delete',
  });
  const aliasAddress = `ci+${alias.tag}@qa.acme.mailfork.dev`;

  const verifyUrl = await mfPlayer.waitForUrl(page, INBOX_ID, async () => {
    await page.goto('/signup');
    await page.fill('[name=email]', aliasAddress);
    await page.click('#send-verification');
  }, {
    button_text: 'Verify Email',
    alias_tag: alias.tag,
  });

  await page.goto(verifyUrl);
  await expect(page).toHaveURL('/onboarding');
});
8

Error Handling

The SDK exports typed errors. Catch and handle them explicitly.

import { NotFoundError, QuotaError, AuthError, ValidationError } from '@mailfork/sdk';

try {
  const url = await mf.emails.extractUrl(INBOX_ID, {
    button_text: 'Verify Email',
    wait_timeout_ms: 15_000,
  });
} catch (err) {
  if (err instanceof NotFoundError) {
    throw new Error('Verification email did not arrive within timeout');
  }
  if (err instanceof QuotaError) {
    throw new Error('Daily API quota exceeded');
  }
  if (err instanceof AuthError) {
    throw new Error('API key invalid or missing scope');
  }
  if (err instanceof ValidationError) {
    throw new Error('Bad request parameters');
  }
  throw err;
}
Common errors:
  • NotFoundError — Email did not arrive within timeout
  • QuotaError — API quota exceeded for your plan
  • AuthError — API key missing, invalid, or lacks required scope