Docs / OTP Extraction

Guide 4 of 8

OTP Extraction

MailFork extracts OTP codes automatically. A single SDK call polls until the email arrives, then returns the extracted code. Requires the emails:read scope on your API key.


Basic OTP Extraction

TypeScript
const result = await mf.emails.extractOtp({
  inbox: 'ci@qa.acme.mailfork.dev',
  waitTimeoutMs: 15000,
  receivedAfter: new Date(Date.now() - 5 * 60 * 1000), // last 5 minutes only
});

console.log(result.otp); // "482910"
Auto-detect mode: When no pattern is provided, MailFork uses a ranked library of common OTP patterns (6-digit codes, "Your code is X", "verification code: X", and more) and returns the highest-confidence match.

Using an Alias recommended

Scoping to an alias means OTPs from parallel runs don't interfere. Each run gets its own alias tag — reads are isolated automatically.
TypeScript
const result = await mf.emails.extractOtp({
  inbox: 'ci@qa.acme.mailfork.dev',
  aliasTag: 'run-42',
  waitTimeoutMs: 15000,
});

console.log(result.otp); // "482910"

Custom Regex Pattern

If your app sends OTPs in a non-standard format, provide a pattern. The pattern is matched against the full email body. The first capture group is returned as the OTP.

TypeScript
const result = await mf.emails.extractOtp({
  inbox: 'ci@qa.acme.mailfork.dev',
  pattern: 'verification code[:\\s]+([0-9]{6})',
  waitTimeoutMs: 15000,
});

console.log(result.otp); // "482910"
The pattern is a JavaScript-compatible regular expression string. The first capture group (...) is what gets returned as result.otp.

Confidence Score

Every extraction result includes a confidence value from 0.0 to 1.0. Scores below 0.6 indicate the match may be unreliable — the pattern matched but the surrounding context didn't strongly resemble an OTP email. Treat low-confidence results with caution.

TypeScript
const result = await mf.emails.extractOtp({
  inbox: 'ci@qa.acme.mailfork.dev',
  waitTimeoutMs: 15000,
});

console.log(result.otp);        // "482910"
console.log(result.confidence); // 0.95

if (result.confidence < 0.6) {
  console.warn('Low confidence OTP match — verify manually');
}

Timeout and Not Found

If no matching email arrives within waitTimeoutMs, the SDK throws an OtpNotFoundError. Catch it to handle the failure case explicitly.

TypeScript
import { MailForkClient, OtpNotFoundError } from '@mailfork/sdk';

try {
  const result = await mf.emails.extractOtp({
    inbox: 'ci@qa.acme.mailfork.dev',
    waitTimeoutMs: 15000,
  });
  console.log(result.otp);
} catch (e) {
  if (e instanceof OtpNotFoundError) {
    // No OTP email arrived within 15 seconds
    // Check that your app is actually sending the email
    console.error('OTP not received in time');
  } else {
    throw e;
  }
}