惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
雷峰网
雷峰网
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
G
Google Developers Blog
腾讯CDC
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Microsoft Security Blog
Microsoft Security Blog
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
C
Check Point Blog
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
Y
Y Combinator Blog
L
LangChain Blog
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Extract OTP Codes From Email, Automatically
Qasim Muhammad · 2026-06-12 · via DEV Community

Qasim Muhammad

What does your automation do when the login flow it's driving sends a six-digit code instead of a confirmation link? For most teams the honest answer is "a human goes and checks a shared inbox," which is a strange bottleneck to leave in the middle of an otherwise fully automated pipeline.

There's a cleaner shape: the agent owns the mailbox the code lands in. With a Nylas Agent Account — a hosted mailbox controlled entirely through the API, currently in beta — the OTP email arrives, a webhook fires, your handler extracts the code, and whatever orchestrates the login gets it back. No human, no inbox-checking Slack message, no screen-scraping Gmail.

Step one: make sure it's the right email

A message.created webhook fires on every inbound message, so the first job is filtering down to the one that actually carries the code. The recipe uses two signals together — sender domain and a subject heuristic:

app.post("/webhooks/otp", async (req, res) => {
  res.status(200).end();

  const event = req.body;
  if (event.type !== "message.created") return;

  const msg = event.data.object;
  if (msg.grant_id !== AGENT_GRANT_ID) return;

  const sender = msg.from?.[0]?.email ?? "";
  const subject = msg.subject ?? "";

  const senderMatches = sender.endsWith("@no-reply.example.com");
  const subjectLooksRight = /code|verif|one.?time|passcode/i.test(subject);
  if (!senderMatches || !subjectLooksRight) return;

  await handleOtp(msg.id);
});

Neither check alone is enough. Sender-only matching trips on welcome emails from the same domain; subject-only matching trips on anything that mentions "verification."

Regex first, LLM second

Most OTP emails follow one of a few shapes: a standalone 4–8 digit number, or a code after a label like "Your code is:". Three patterns, tried in order from most to least specific, cover the vast majority of services:

const patterns = [
  /(?:code|passcode|one[\s-]?time)[^\d]{0,20}(\d{4,8})/i, // "Your code is: 123456"
  /\b(\d{6})\b/,        // bare 6-digit
  /\b(\d{4,8})\b/,      // bare 4–8 digit (last resort)
];

One detail that's easy to miss: strip the HTML before matching. Inline styles and hidden tracking pixels are full of digit sequences that will happily satisfy your last-resort pattern.

When regex strikes out — usually a code buried in a noisy marketing layout — fall back to a small LLM with a deliberately narrow prompt:

async function extractWithLlm(plaintext) {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      {
        role: "system",
        content:
          "You extract one-time verification codes from email bodies. " +
          "Respond with JSON only: {\"code\": \"<the code>\"} or " +
          "{\"code\": null} if no code is present.",
      },
      { role: "user", content: plaintext.slice(0, 4000) },
    ],
    response_format: { type: "json_object" },
  });

  const parsed = JSON.parse(response.choices[0].message.content);
  if (parsed.code) return returnCode(parsed.code);
}

Only the first 4,000 characters of plaintext go in, and the model is asked for one thing in one shape — JSON with a code field or null. Don't ask the model to "understand" the email. Banking and enterprise senders sometimes rotate formats across sessions (6 digits, 8 digits, alphanumeric), and the LLM fallback is what absorbs those shifts without a regex update.

Getting the code back to whoever's waiting

The signup or login that triggered all this is blocked, waiting. The simplest bridge is a promise registry keyed by a correlation value — session ID, expected sender, run ID — with a timeout (the recipe defaults to 60 seconds):

export function awaitCode(correlationKey, timeoutMs = 60_000) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      pending.delete(correlationKey);
      reject(new Error("OTP timeout"));
    }, timeoutMs);
    pending.set(correlationKey, { resolve, reject, timer });
  });
}

In production, swap the in-memory Map for a real queue or pub/sub — webhook handlers run on short-lived processes, and a restart between "code arrived" and "code consumed" loses the code.

The failure modes that actually bite

The recipe's warning list is the best part, because each item is a production incident in miniature:

  • Codes expire fast. Most services invalidate OTPs in 5–15 minutes. Check message.date freshness before returning a code — a slow agent will confidently hand back a dead one.
  • Multiple codes in the inbox. A stale code from an earlier attempt plus a fresh one means your regex can grab the wrong match. Sort by message timestamp, newest first, always.
  • Never log the code. OTPs are credentials. Log that one was received and returned; never the value.
  • Back off on failure. A tight retry loop requesting code after code looks like an attack from the service's side and gets the agent's address blocked.
  • Dedup redelivered webhooks. Nylas delivers webhooks at least once. A redelivered message.created can re-trigger extraction and hand a stale code back to a fresh login attempt — the duplicate-reply prevention patterns apply here too.

There's also a defense you set up before any of this code runs: lock the inbox down at the mail layer. Agent Account policies and rules can constrain inbound so only expected sender domains ever reach the agent's inbox. An OTP mailbox that accepts mail from anyone is an OTP mailbox someone will eventually try to confuse with look-alike messages; an allowlist makes the "match the right email" step mostly a formality.

Quick answers

What about magic links instead of codes? Same architecture, different regex — match a URL pattern instead of digits and follow the link instead of returning a value. The signup recipe covers that variant.

Why fetch the message body separately? The message.created webhook payload only carries summary fields — sender, subject, snippet. The full body comes from GET /v3/grants/{grant_id}/messages/{message_id}, which is the first call inside the extraction handler.

Why not just use the LLM for everything? Cost and latency, but mostly determinism. Regex either matches or it doesn't; you want the probabilistic component to be the fallback, not the front door.

Where this slots in

OTP extraction is rarely the whole feature — it's the middle step of something bigger, usually an agent signing up for a third-party service end to end: provision the mailbox, submit the form, catch the verification, finish onboarding. The link-based variant of verification is the same architecture with a URL regex instead of a digit regex.

Try this with a service you control first: point a test signup at the agent's address, watch the webhook land, and check which of the three regex tiers actually matched. If you've built OTP extraction before — what's the weirdest code format you've had to parse? I'm collecting nominations.