iToverDose/Software· 24 JUNE 2026 · 04:06

Automate OTP and 2FA code extraction with Nylas for seamless logins

Tired of manually copying one-time passcodes from emails? Discover how Nylas’ CLI and API can automate OTP extraction, saving time in scripts, tests, and login flows without tedious parsing.

DEV Community4 min read0 Comments

Retrieving one-time passcodes (OTPs) and two-factor authentication (2FA) codes from emails can feel like a trivial task for humans—but for automation, it’s a persistent hurdle. Whether you’re writing a signup script, executing end-to-end tests, or building an AI agent that interacts with third-party services, extracting these six-digit codes from templated emails requires precision. The challenge intensifies because each sender formats messages differently, and the code arrives mere seconds after the trigger, buried in email content that isn’t always predictable.

Fortunately, Nylas offers two complementary approaches to streamline this process: a command-line interface (CLI) for quick retrieval and an API-based pattern for integrating OTP extraction into larger workflows. The CLI provides a fast, developer-friendly solution for local testing and scripting, while the API approach delivers a scalable, event-driven system suitable for production environments.

Two methods for retrieving OTPs: CLI vs. API-driven workflows

The choice between these approaches depends on your use case. If you’re working in a terminal, debugging a script, or need a code on demand, the Nylas CLI offers a dedicated nylas otp command that retrieves the latest passcode from a specified mailbox. This method is pull-based—you explicitly request the code when needed.

For applications, agents, or services that must react dynamically to incoming emails, the API-based method is ideal. It uses a push model: a webhook notifies your system when a new message arrives, and your code then extracts the code from the email body. While both approaches ultimately return the same string of digits, the CLI excels in developer convenience, while the API ensures durability and integration into broader systems.

In practice, many developers use both: the CLI during development to identify the sender and code format, and the API pattern in production to automate the process without manual intervention.

Retrieve OTPs instantly using the Nylas CLI

The Nylas CLI simplifies OTP retrieval with just one command. Running nylas otp get fetches the most recent code from your default connected email account and presents it directly in the terminal. By default, the command also copies the code to your clipboard, making it easy to paste into a login form or script.

nylas otp get

To target a specific email account, append the address as an argument. If you need the raw code without any formatting or clipboard behavior—ideal for scripting—use the --raw and --no-copy flags. This ensures the output is clean and suitable for variable assignment in scripts:

nylas otp get user@example.com --raw --no-copy

For structured output, the --json flag returns the code in a machine-readable format, which is useful when integrating with other tools or logging systems.

Monitor emails in real time with the watch command

In workflows where you trigger a login or action and immediately await the OTP, polling manually is inefficient. The nylas otp watch command solves this by continuously monitoring the inbox and surfacing the code as soon as it arrives. This is particularly handy for demo setups or interactive testing where you want the code delivered instantaneously.

nylas otp watch user@example.com --interval 5

The --interval flag lets you control how often the command checks for new messages, with a default of 10 seconds. Reducing this to 5 seconds minimizes perceived wait times without overloading the email provider. Like the get command, watch also copies the code to your clipboard unless you disable it with --no-copy.

This real-time monitoring streamlines manual login flows: trigger the authentication request, switch to your terminal, and the code is ready to use by the time you return.

Integrate OTP extraction into your application via API

While the CLI suits interactive use, production systems require an automated, event-driven approach. The Nylas API pattern involves subscribing to a webhook that triggers whenever a new email arrives. Upon receiving the notification, your application fetches the email body and extracts the OTP programmatically.

This method follows a three-step process. First, filter incoming webhook events to isolate the verification email, typically by sender address or timestamp. Next, retrieve the full email content using the Nylas Messages API endpoint. Finally, parse the six-digit code from the message body.

A minimal webhook handler could look like this in JavaScript:

app.post("/webhooks/nylas", async (req, res) => {
  res.sendStatus(200); // Acknowledge receipt immediately
  
  const msg = req.body.data.object;
  if (!isFromExpectedSender(msg)) return; // Skip irrelevant emails
  
  const full = await nylas.messages.find({
    identifier: GRANT_ID,
    messageId: msg.id,
  });
  
  const code = extractCode(full.data.body);
  if (code) await submitCode(code); // Forward the code to your system
});

This design ensures the OTP is processed as soon as the email lands, eliminating the need for custom polling logic and improving reliability.

Extract codes with regex for speed, LLM for flexibility

Most verification emails follow predictable patterns that can be parsed using regular expressions. A simple pattern like \b(\d{6})\b captures a six-digit code from the body, making it fast, deterministic, and cost-free to implement:

const match = body.match(/\b(\d{6})\b/);
const code = match ? match[1] : null;

Before applying the regex, ensure you’re working with plain text—strip HTML tags if necessary—to avoid false matches from hidden attributes or tracking pixels. For services that use codes of varying lengths, adjust the pattern to \b(\d{4,8})\b, which captures codes between four and eight digits.

For edge cases where email formats deviate from standard templates, consider using a lightweight language model as a fallback. While regex handles 90% of scenarios efficiently, LLMs can interpret unstructured or highly customized email layouts without manual rule adjustments. This hybrid approach balances performance with adaptability, ensuring robust OTP extraction across diverse senders.

AI summary

Learn how to automate one-time passcode and 2FA code extraction from emails using Nylas CLI and API. Build faster scripts, tests, and login flows with these proven methods.

Comments

00
LEAVE A COMMENT
ID #GFAFOB

0 / 1200 CHARACTERS

Human check

9 + 2 = ?

Will appear after editor review

Moderation · Spam protection active

No approved comments yet. Be first.