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

推荐订阅源

T
Tenable Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Cloudflare Blog
美团技术团队
Recorded Future
Recorded Future
T
Tailwind CSS Blog
Latest news
Latest news
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Cloudbric
Cloudbric
Schneier on Security
Schneier on Security
I
Intezer
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
L
LangChain Blog
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
SecWiki News
SecWiki News
V2EX - 技术
V2EX - 技术
IT之家
IT之家
Cyberwarzone
Cyberwarzone
F
Full Disclosure
Spread Privacy
Spread Privacy
阮一峰的网络日志
阮一峰的网络日志

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Pull OTP and 2FA codes from email with Nylas
Qasim · 2026-06-24 · via DEV Community

One-time passcodes are everywhere: sign up for a service, log in from a new device, confirm an action, and a six-digit code lands in your email. A human glances at it and types it in. An automated flow, a signup script, an end-to-end test, or an AI agent connecting to a third-party service, can't glance at anything. It has to pull the code out of the mailbox programmatically, and that's a surprisingly fiddly job: the code arrives seconds after a trigger, it's buried in a templated email, and every sender formats it differently.

This post covers extracting verification codes from two angles: the nylas CLI, which does it for you in one command, and the Email API pattern you build when it's part of a larger flow. I work on the CLI, so the terminal commands below are the ones I reach for when I just need the code.

Two ways to get the code

There are two paths depending on what you're building. For terminal workflows, local testing, or scripting a login, the CLI has a dedicated nylas otp command that finds the latest code in a mailbox and hands it to you. For an application or an agent that reacts to incoming mail, you build the extraction into your own flow: catch the message when it arrives, pull the body, and parse the code out.

The difference is who drives. The CLI is pull-based: you ask for the latest code when you need it. The API pattern is push-based: a webhook tells you a message arrived, and your code extracts the value as part of handling it. Both end at the same place, a string of digits you feed into whatever's waiting for it, but the CLI is the fast path for a developer and the API pattern is the durable path for a product. In practice you use both: the CLI to learn which sender and code format you're dealing with during development, then that same understanding baked into the application pattern for production.

Grab the latest code from the CLI

When you've just triggered a code and want it now, nylas otp get finds the most recent one in your default account and returns it. By default it also copies the code to your clipboard, so in interactive use you can trigger the send, run the command, and paste straight into the form. Pass an email address to target a specific connected account.

# Latest code from the default account
nylas otp get

# From a specific account, code only, no clipboard
nylas otp get user@example.com --raw --no-copy

The --raw flag prints only the code with no surrounding text, which is what you want when you're capturing it in a script: CODE=$(nylas otp get --raw --no-copy) gives you the bare value in a variable. The --no-copy flag skips the clipboard, which matters in automation where there's no clipboard to write to and you don't want the side effect. For a readable, scriptable object instead, --json returns the structured result.

Watch for a code as it arrives

Often you trigger the code first and it lands a moment later, so polling once is a race. nylas otp watch solves that by watching the mailbox and surfacing the code the instant it shows up, checking on an interval until one arrives. It's the command for the common sequence of "submit the form, then wait for the email."

# Watch for a new code, checking every 5 seconds
nylas otp watch user@example.com --interval 5

The --interval flag sets how often it checks, defaulting to 10 seconds; tightening it to 5 makes the wait feel instant in a demo without hammering the provider. Like get, it copies the code to your clipboard unless you pass --no-copy. The watch pattern is what makes a manual login flow smooth: kick off the request, switch to the terminal, and the code is waiting by the time you look.

Build extraction into your application

The CLI is perfect for a developer at a keyboard, but an agent or backend service needs the extraction inside its own logic. There's no dedicated OTP endpoint to call; instead you assemble it from pieces you already have. The reliable shape is event-driven: subscribe to the message.created webhook, and when a message arrives, fetch its body and parse the code out.

The flow is three steps. First, the webhook fires for every inbound message, so you filter down to the one that actually carries the code, usually by sender or by how recently it arrived relative to the action that triggered it. Second, you fetch that message's body with GET /v3/grants/{grant_id}/messages/{message_id}. Third, you extract the digits. Building it this way means the code lands in your workflow the moment the email does, with no polling loop of your own.

A webhook handler that ties these steps together stays small. You acknowledge the delivery fast, ignore anything that isn't the verification email, fetch the body, and extract the code:

app.post("/webhooks/nylas", async (req, res) => {
  res.sendStatus(200); // acknowledge first, then work
  const msg = req.body.data.object;
  if (!isFromExpectedSender(msg)) return;
  const full = await nylas.messages.find({
    identifier: GRANT_ID,
    messageId: msg.id,
  });
  const code = extractCode(full.data.body);
  if (code) await submitCode(code);
});

Extract with regex first, an LLM as fallback

Most verification emails put the code somewhere a simple pattern can find it, so start with a regular expression. A pattern for a standard six-digit code is enough for the large majority of OTP and 2FA emails, and it's fast, free, and deterministic.

// Pull a 6-digit code from the message body
const match = body.match(/\b(\d{6})\b/);
const code = match ? match[1] : null;

Run the pattern against the plain-text body, or strip the HTML first, so it matches the visible code and not digits hidden in inline styles or a tracking pixel. If your codes vary in length, widen the pattern to \b(\d{4,8})\b to catch four- through eight-digit codes, and anchor on a nearby word like "code" or "verification" when a message also carries other numbers. Don't over-engineer it, though: past a point, the fallback below handles edge cases more reliably than an increasingly complicated pattern.

Regex falls down on the messy cases: a code split by spaces, an unusual length, or a template where the digits sit next to an order number you'd match by mistake. That's where an LLM fallback earns its place. When the regex returns nothing or something ambiguous, hand the body to a model with a tight prompt like "extract only the login verification code from this email," and let it handle the formatting the pattern missed. Regex-first keeps the common path cheap, and the model only runs on the emails that actually need it.

Filter down to the right message

The hardest part isn't reading the code, it's making sure you read the right email. A mailbox gets other mail, and a stale code from an hour ago is worse than no code, since it'll fail the form and look like a bug. Two filters do most of the work: match the sender the codes come from, and take only messages newer than the moment you triggered the request.

Both filters are query parameters on the messages endpoint: from matches the sender address, and received_after takes a Unix timestamp so you only see mail that arrived after your trigger. A single list call with both narrows the candidates to the one message that matters, before you fetch a body or run any extraction. For an agent signing up to a service, you often know the sending domain in advance, which makes the sender filter exact rather than a guess, and the recency window can be tight because the code arrives within seconds of the request.

Use it in end-to-end tests

End-to-end tests that exercise a real login can't stub the verification step without testing a fake. nylas otp get --raw --no-copy slots into a test harness: the test submits the login form, then calls the command to retrieve the code from the test mailbox and types it in. Because the value is the real one the provider sent, the test covers the actual flow instead of a mock that drifts from reality.

A dedicated test mailbox, or a Nylas Agent Account spun up per run, keeps this deterministic. Each test gets its own inbox, so parallel runs don't grab each other's codes, and paired with the recency filter a test never picks up a stale code from a previous run. That combination is what turns a notoriously flaky part of UI testing into something that passes reliably in CI.

Put the whole flow together

The pieces add up to an agent that verifies itself with no human in the loop. The agent submits a signup or login to a third-party service using its own email address, the service emails a code, and the agent extracts it and completes the step. With the CLI that's nylas otp watch running while the signup happens; in an application it's the webhook-driven pattern firing the moment the code email lands.

This is the pattern behind automated account provisioning and agent onboarding. The agent owns a real inbox, so it receives the same verification emails a person would, and the extraction step is the bridge between "a code was emailed" and "the agent typed it in." Nothing about it requires someone to be watching the inbox, which is the entire point of giving an agent its own address.

Things to keep in mind

A short list of practices keeps OTP extraction reliable and safe.

  • Use recency to avoid stale codes. An old code fails silently; always take the newest message after your trigger, not just any match.
  • Never log the code. A verification code is a secret; keep it out of logs, traces, and error messages the same way you would a password.
  • Treat codes as short-lived. Most expire in minutes, so extract and use immediately rather than queuing the value for later.
  • Start with regex, escalate to an LLM. The pattern handles the common case cheaply; reserve the model for templates it can't parse.
  • Pin the sender when you can. Knowing the sending domain up front turns a fuzzy search into an exact filter.
  • Pass --no-copy in automation. The CLI copies the code to your clipboard by default, which is handy at a keyboard but a useless side effect in a script or CI run.

Wrapping up

Getting a verification code out of email is a one-liner from the terminal with nylas otp get, or a watch loop with nylas otp watch when you're waiting on a send. In an application, the same job is a small pattern: a message.created webhook tells you mail arrived, you fetch the body, and you extract the code with a regex backed by an LLM for the messy templates. Filter on sender and recency so you read the right message, never log the value, and use it before it expires.

Where to go next: