# Reading of OTP from email

For automated tests of your own app, Humanless is simpler than reading Gmail: it creates a disposable address per test, and `GET /v1/identities/:id/wait` returns the email's OTP already extracted, as soon as the message arrives. It ignores numbers that aren't the code, such as years, prices and phone numbers, and returns the code as a string so leading zeros survive. From Java, that's two HTTP calls with the built-in `HttpClient`. If you must read a Gmail account, use IMAP with an app password or the Gmail API, search by recipient and time, and anchor your regex to the email's wording, not just any six digits.

```java OtpReader.java
// With Humanless: the wait returns the code already parsed. 408 means nothing arrived yet.
static String waitForOtp(String identityId, long since) throws Exception {
  URI wait = URI.create(API + "/" + identityId + "/wait?channel=email&timeout=30&since=" + since);
  long deadline = System.currentTimeMillis() + 120_000;
  while (System.currentTimeMillis() < deadline) {
    HttpResponse<String> res = HTTP.send(HttpRequest.newBuilder(wait).header("Authorization", AUTH).build(),
        HttpResponse.BodyHandlers.ofString());
    if (res.statusCode() == 200) return JSON.readTree(res.body()).path("code").asText(null);
    if (res.statusCode() != 408) throw new IllegalStateException(res.body());
  }
  throw new AssertionError("No OTP email within 2 minutes");
}

// Reading Gmail yourself (IMAP or the Gmail API): anchor the regex to the email's wording,
// so a year, price or order number in the same message isn't taken for the code.
static final Pattern OTP = Pattern.compile("(?i)(?:code|one-time password)\\D{0,30}(\\d{6})\\b");
static String otpFromBody(String bodyText) {
  Matcher m = OTP.matcher(bodyText);
  if (!m.find()) throw new AssertionError("No code in email: " + bodyText);
  return m.group(1);  // keep it a String so leading zeros survive
}
```

## Other options

- **JavaMail / Jakarta Mail over IMAP** with a Gmail app password (requires 2-Step Verification on the Google account).
- **The Gmail API** with an OAuth client and stored refresh token.
- **Mailpit** for test environments where you control the SMTP settings.

> **Use policy:** Only for apps you own or are authorized to test. See the [Terms](/terms).

More: [Humanless REST API reference](/docs/api) · [All answers](/answers/)

Last updated 2026-12-04

Canonical: https://usehumanless.com/answers/reading-of-otp-from-email

---
More: https://usehumanless.com/llms.txt
