Updated: Nov 2026
Selenium cannot check emails itself, so we use an email testing API to check if the correct email was sent. In this article, we’ll use testmail.app’s JSON API to wait for emails and extract codes or links from them, all using Selenium and Java’s built-in HttpClient. Each test gets a unique inbox address: Selenium fills in the signup or reset form, then uses the email’s code or link to finish the flow in the same browser. No IMAP setup or shared mailbox is needed.
By the end of this article, you’ll know how to use Selenium WebDriver to fill signup and password reset forms, wait for emails to be received using testmail.app’s JSON API, extract verification codes and links using Java, check links and spam scores, and run tests in parallel and on GitHub Actions. This project uses Java 17 or later, Selenium 4.52 (which downloads ChromeDriver for you), JUnit 6 and one inbox helper. With testmail.app, every address at your namespace is an inbox and one request waits for the email to arrive.
How a Selenium email test works
Here’s a high-level overview of how these tests work:
- Generate a unique random email address for this test and store it in a variable.
- Use Selenium to navigate to your signup (or login or password reset) page and fill the form using the random email address.
- Your application sends an account verification (or password reset) email to that random email address using its transactional email service.
- Use Java’s
HttpClientto send a GET request to testmail.app’s JSON API to fetch the next email sent to the random email address. This API request blocks until an email is received at that email address. - Extract the code or link from the email’s contents. Use Selenium to enter the code or navigate to that link and finish the flow in the same browser.

one signup test, top to bottom · JUnit, Chrome, your app, testmail.app
The live query is what replaces Thread.sleep(): the request is already open when your app sends the email, and testmail.app answers it the moment the email lands.
Many of the answers to Selenium email testing questions on Stack Overflow use the Gmail API or IMAP to fetch emails. Those approaches work too, but require much more setup than using a service like testmail.app.
| How the test reads email | What it needs | Problems in a suite |
|---|---|---|
| IMAP to a real mailbox (Jakarta Mail) | A mailbox, plus an app password or OAuth for most providers | One inbox shared by every test, polling, and providers tightening IMAP access |
| Gmail API | A Google Cloud OAuth client and tokens | Polling, one inbox, and refresh tokens for unpublished apps expire after 7 days |
| An email testing API | An API key | None of the above: every test gets its own address, and one request waits for the email |
We’ll use JDK HttpClient to interact with testmail.app’s JSON API.

Set up the project
This project uses JDK 17 or later, Maven 3.9 or later, and Chrome. JUnit 6 requires Java 17. We don’t need to download ChromeDriver because since version 4.6, Selenium includes Selenium Manager which automatically downloads the correct version of ChromeDriver for us the first time a test runs.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>email-tests</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.52.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>6.1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20260814</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</build>
</project>We’ll use JDK HttpClient to interact with testmail.app’s JSON API, org.json to parse the JSON responses and jsoup to extract links from the emails’ HTML contents. There’s no HTTP client library to add. Export the following three environment variables (replacing the values where necessary):

export TESTMAIL_APIKEY=your-api-key
export TESTMAIL_NAMESPACE=your-namespace
export BASE_URL=http://localhost:3000The TESTMAIL_APIKEY and TESTMAIL_NAMESPACE environment variables can be found on the testmail.app console. The tests read these environment variables (along with BASE_URL, the address of the app under test) using System.getenv() so we don’t have to commit our API key to source control.
The inbox helper
This class will be used by the test classes to wait for emails to be received and extract data from them. Each instance is a fresh address, {namespace}.{tag}@inbox.testmail.app, which exists as soon as something sends to it, so there’s nothing to create or delete.
// src/test/java/com/example/email/TestInbox.java
package com.example.email;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
/** One testmail.app inbox per test: {namespace}.{tag}@inbox.testmail.app */
public final class TestInbox {
private static final String API = "https://api.testmail.app/api/json";
private static final String NAMESPACE = System.getenv("TESTMAIL_NAMESPACE");
private static final String APIKEY = System.getenv("TESTMAIL_APIKEY");
private static final Pattern SIX_DIGITS = Pattern.compile("\\b\\d{6}\\b");
private static final HttpClient HTTP = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL) // live queries re-issue themselves with a 307
.build();
public final String tag = "selenium." + UUID.randomUUID().toString().substring(0, 8);
public final String address = NAMESPACE + "." + tag + "@inbox.testmail.app";
private long since = System.currentTimeMillis();
/** Waits on testmail.app's side for the next email to this inbox. */
public JSONObject next() throws Exception {
return next(false);
}
public JSONObject next(boolean spamReport) throws Exception {
String url = API + "?apikey=" + enc(APIKEY) + "&namespace=" + enc(NAMESPACE) + "&tag=" + enc(tag)
+ "×tamp_from=" + since + "&livequery=true" + (spamReport ? "&spam_report=true" : "");
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(75)).GET().build();
JSONObject body = new JSONObject(HTTP.send(request, HttpResponse.BodyHandlers.ofString()).body());
if (!"success".equals(body.getString("result"))) {
throw new IllegalStateException("testmail.app: " + body.optString("message"));
}
JSONArray emails = body.getJSONArray("emails"); // newest first
if (emails.length() == 0) {
throw new IllegalStateException("No email for " + address);
}
JSONObject email = emails.getJSONObject(emails.length() - 1); // the oldest email not seen yet
since = email.getLong("timestamp") + 1; // the next call waits for a newer one
return email;
}
/** The first six-digit number in the plain-text part. */
public static String code(JSONObject email) {
Matcher match = SIX_DIGITS.matcher(email.getString("text"));
if (!match.find()) {
throw new AssertionError("No six-digit code in \"" + email.getString("subject") + "\"");
}
return match.group();
}
/** The first link whose URL contains the given path; Jsoup decodes & for you. */
public static String link(JSONObject email, String path) {
for (Element a : Jsoup.parse(email.getString("html")).select("a[href]")) {
String href = a.attr("href");
if (href.contains(path)) {
return href;
}
}
throw new AssertionError("No link containing " + path + " in \"" + email.getString("subject") + "\"");
}
private static String enc(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}What each part does:
TestInbox’s one trick is that itslivequery=trueparameter tells the API to wait for an email matching the tag. If an email matching the tag has already been received,livequery=truewill return that immediately (that’s where the movingtimestamp_fromparameter comes in). If there isn’t one within a minute, the API returns an HTTP 307 redirect to itself, andRedirect.NORMALmeansHttpClientwill follow the redirect. This way, waiting happens on the server side.timestamp_fromstarts at the moment the inbox was created and moves past each emailnext()returns. That's what lets a password reset test skip the verification email that arrived first; a live query otherwise returns at once if any email matches.- The 75-second request timeout is long enough to cover one full live-query hold. The
@Timeoutannotation on the test class will make sure that the test doesn’t hang the entire test run if the email doesn’t show up. - Here,
code()extracts a verification code, which we assume is in the email’s plain-text version (so it isn’t broken up by HTML table cells, for example). If it finds nothing, it fails with the subject in the message. link()extracts a hyperlink, if your app uses one-click links instead of codes. Notice that it uses jsoup to parse the HTML and extract the link, which has the advantage of turning&back into & in anhref(important, for example, if your links have signatures). A regular expression over raw HTML leaves&in and breaks signed links.
Test signup verification
We use WebDriverWait instead of Thread.sleep() to wait for elements to appear. Each test starts its own headless Chrome. Form field names, the submit button and the /dashboard URL are placeholders for your app’s own.
// src/test/java/com/example/email/SignupEmailTest.java
package com.example.email;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import org.json.JSONObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Timeout(120) // seconds: a missing email fails the test instead of hanging the build
class SignupEmailTest {
private static final String BASE_URL = System.getenv().getOrDefault("BASE_URL", "http://localhost:3000");
private static final String PASSWORD = "correct horse battery staple";
private WebDriver driver;
private WebDriverWait wait;
@BeforeEach
void startBrowser() {
ChromeOptions options = new ChromeOptions().addArguments("--headless=new", "--window-size=1280,900");
driver = new ChromeDriver(options); // Selenium Manager fetches a matching chromedriver
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@AfterEach
void stopBrowser() {
driver.quit();
}
private void startSignup(TestInbox inbox) {
driver.get(BASE_URL + "/signup");
driver.findElement(By.name("email")).sendKeys(inbox.address);
driver.findElement(By.name("password")).sendKeys(PASSWORD);
driver.findElement(By.cssSelector("button[type=submit]")).click();
}
private void enterCode(String code) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("code"))).sendKeys(code);
driver.findElement(By.cssSelector("button[type=submit]")).click();
}
private void signUp(TestInbox inbox) throws Exception {
startSignup(inbox);
enterCode(TestInbox.code(inbox.next()));
wait.until(ExpectedConditions.urlContains("/dashboard"));
}
@Test
void verificationCodeActivatesTheAccount() throws Exception {
TestInbox inbox = new TestInbox();
startSignup(inbox);
JSONObject email = inbox.next();
assertTrue(email.getString("from").contains("no-reply@yourapp.com"), "sender");
assertTrue(email.getString("subject").toLowerCase().contains("verify"), "subject");
enterCode(TestInbox.code(email));
wait.until(ExpectedConditions.urlContains("/dashboard"));
}
@Test
void verificationLinkActivatesTheAccount() throws Exception {
TestInbox inbox = new TestInbox();
startSignup(inbox);
driver.get(TestInbox.link(inbox.next(), "/verify")); // same browser session as the signup
wait.until(ExpectedConditions.urlContains("/dashboard"));
}
// the password reset test from the next section goes here
}Note that the email’s from field includes a display name, e.g. Your App <no-reply@yourapp.com>. That’s why we use contains to check the from field. Note that we don’t open a new browser to click on the link; we use the same driver. This way, any cookies set by the signup form will be present when the verification link is opened (some websites only allow the link to be opened in the same browser it was requested from). For codes that expire, resend limits and lockouts, see the email OTP testing guide; for one-click sign-in links, the magic link testing guide has a Selenium section.
Test the password reset email
Now let’s test the password reset email. For that, we’ll use the helper above to sign up a new user (which has to read the verification email anyway). Note that this time, we’re using next() twice: once to read the verification email when signing up, which also means the second call to next() will wait for the reset email instead of immediately returning the verification email again. Let’s add a test to the SignupEmailTest class above:
@Test
void passwordResetEmailSetsANewPassword() throws Exception {
TestInbox inbox = new TestInbox();
signUp(inbox); // reads the verification email
driver.get(BASE_URL + "/forgot-password");
driver.findElement(By.name("email")).sendKeys(inbox.address);
driver.findElement(By.cssSelector("button[type=submit]")).click();
JSONObject reset = inbox.next(); // skips the verification email
assertTrue(reset.getString("subject").toLowerCase().contains("reset"), "subject");
driver.get(TestInbox.link(reset, "/reset-password"));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("password"))).sendKeys("a brand new passphrase");
driver.findElement(By.cssSelector("button[type=submit]")).click();
driver.get(BASE_URL + "/login");
driver.findElement(By.name("email")).sendKeys(inbox.address);
driver.findElement(By.name("password")).sendKeys("a brand new passphrase");
driver.findElement(By.cssSelector("button[type=submit]")).click();
wait.until(ExpectedConditions.urlContains("/dashboard"));
}The login at the end is the real assertion: a reset page can show "Password updated" while the old password still works. There are two more password reset scenarios worth testing once this passes. Reset a password and try to use the reset link again: it should tell you the link has expired or already been used. Request two password reset emails in a row: only the link from the most recent email should work. See our Selenium password reset guide for more details.
Check the email itself, without a browser
Some tests don’t need Selenium. For example, to check that an email was received and contains certain information. These tests will only take a couple of seconds to run (plus the time it takes for your app to send the email). Trigger the email through your API and inspect what arrives; /api/signup is a placeholder for whatever your app uses.
// src/test/java/com/example/email/EmailContentTest.java
package com.example.email;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
/** Checks on the email itself. No browser needed: the signup is triggered through the API. */
@Timeout(120)
class EmailContentTest {
private static final String BASE_URL = System.getenv().getOrDefault("BASE_URL", "http://localhost:3000");
private static final HttpClient HTTP = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build();
private static JSONObject signupEmail(TestInbox inbox, boolean spamReport) throws Exception {
String json = new JSONObject().put("email", inbox.address).put("password", "correct horse battery staple").toString();
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + "/api/signup"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
int status = HTTP.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
assertTrue(status < 300, "signup returned " + status);
return inbox.next(spamReport);
}
@Test
void everyOtherLinkResolves() throws Exception {
JSONObject email = signupEmail(new TestInbox(), false);
for (Element a : Jsoup.parse(email.getString("html")).select("a[href^=http]")) {
String href = a.attr("href");
if (href.contains("/verify")) {
continue; // opening it would use up the token
}
int status = HTTP.send(HttpRequest.newBuilder(URI.create(href)).GET().build(),
HttpResponse.BodyHandlers.discarding()).statusCode();
assertTrue(status < 400, href + " returned " + status);
}
}
@Test
void spamScoreStaysLow() throws Exception {
JSONObject email = signupEmail(new TestInbox(), true);
double score = email.getDouble("spam_score");
assertTrue(score < 5, "SpamAssassin score " + score + "\n" + email.optString("spam_report"));
}
}Follow redirects to make sure click-tracking links work; don’t test links that mutate state (like the verification link, which we’re testing separately). You can also ask testmail.app to analyse the email for spamminess (spam_report=true); this will add a spam_report field with SpamAssassin’s full output, and a spam_score field with its spam score. If the latter is 5 or higher (SpamAssassin’s default threshold for considering an email spammy), the assertion prints the spam_report so you can see which rules tripped.
Run the tests in parallel
Since each test creates its own TestInbox, you can safely run tests in parallel, as they won’t be reading each other’s emails. Enable JUnit’s parallel test execution feature by adding the following file, src/test/resources/junit-platform.properties:
# every test has its own inbox, so they can run at the same time
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = 4By default, JUnit will also create a new instance of your test class for each test method, so each test will get its own driver field and thus its own Chrome instance. Chrome instances are relatively memory hungry, so we’d start with the number of cores on the machine and increase only if you know your test runner has some breathing room. If your app rate-limits signups per IP address, relax that limit for test traffic, since every test signs up from the same runner.
Run them in CI
GitHub’s prebuilt Ubuntu runners have Chrome preinstalled, and Selenium Manager will automatically download a matching version of the driver, so all we need to provide is Java, our secrets, and an environment URL:
# .github/workflows/email-tests.yml
name: email-tests
on: [push, pull_request]
jobs:
selenium:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: '21'
cache: maven
- name: Run email tests
run: mvn -B test
env:
BASE_URL: https://staging.yourapp.com
TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
TESTMAIL_NAMESPACE: ${{ vars.TESTMAIL_NAMESPACE }}
- uses: actions/upload-artifact@v7
if: failure()
with:
name: test-results
path: |
target/surefire-reports
target/screenshotsNote that this environment needs to actually send emails, so point it at your normal email provider but restrict it so that it can only send emails to addresses at inbox.testmail.app. Also note that some email providers have sandbox modes with additional restrictions, for example, Amazon SES in sandbox mode will only send emails to verified recipients. On failure, this workflow will upload screenshots (see next section) as well as Surefire’s test reports, so you’ll be just one click away from seeing assertion error messages (including the subject of received emails and, if relevant, a SpamAssassin report!).
Save a screenshot when a test fails
Error messages tell you what went wrong; screenshots show you where it went wrong. Add the following field to SignupEmailTest (just after the driver field, so that it’s in scope for the lambda). This requires the following imports: java.nio.file.Files, java.nio.file.Path, org.junit.jupiter.api.extension.AfterTestExecutionCallback, org.junit.jupiter.api.extension.RegisterExtension, org.openqa.selenium.OutputType and org.openqa.selenium.TakesScreenshot:
// Runs right after a test method and before @AfterEach, so the browser is still open
@RegisterExtension
final AfterTestExecutionCallback screenshotOnFailure = context -> {
if (context.getExecutionException().isPresent() && driver instanceof TakesScreenshot camera) {
Path file = Path.of("target", "screenshots", context.getRequiredTestMethod().getName() + ".png");
Files.createDirectories(file.getParent());
Files.write(file, camera.getScreenshotAs(OutputType.BYTES));
}
};JUnit will invoke our AfterTestExecutionCallback right after running each test method but before running @AfterEach methods, meaning that driver.quit() won’t have shut down our browser instance yet. This will leave behind a PNG image (uploaded by our GitHub workflow alongside Surefire’s reports) for each failed test, conveniently named after the test method.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
The test fails after 120 seconds at inbox.next() | No email reached that address: the app sent elsewhere, or the environment can't send to outside addresses | Print inbox.address, check the provider's activity log, and check sandbox restrictions |
IllegalStateException: No email for … straight away | The livequery parameter is misspelled, so the API answered without waiting | It's all lowercase: livequery=true |
HttpTimeoutException during the wait | A proxy or firewall cuts long-held connections | Allow api.testmail.app through the proxy without an idle timeout under 75 seconds |
| "This version of ChromeDriver only supports Chrome version …" | An old chromedriver on the PATH is used instead of Selenium Manager's | Remove it from the PATH and let Selenium 4.52 pick the matching driver |
NoSuchElementException right after a click | The next page hasn't rendered yet | Wait with ExpectedConditions.visibilityOfElementLocated instead of calling findElement straight away |
| The reset test receives the verification email | The second wait used a new TestInbox, which starts its own since | Use the same TestInbox object for every email in a test |
AssertionError: No six-digit code in … | The code has a different format, or is only in the HTML part | Change the Pattern, or anchor it to the label text ("code:") |
| The link opens but the token is rejected | The URL still contains &, or it was opened in a different browser session | Use TestInbox.link() and the same driver that did the signup |
| Tests interfere when run in parallel | A static WebDriver shared between tests | Keep the driver as an instance field, as above |
| HTTP 429 from your app during parallel runs | Per-IP signup limits on the shared runner | Relax per-IP limits for test traffic in the test environment |
FAQ
Can Selenium read emails?
Not by itself, as Selenium is for controlling browsers! You can of course supplement your Selenium test with some Java code for reading emails, using an email testing service’s API (as we’ve done here, using Java’s built-in HttpClient), an IMAP client library, the Gmail API, etc. Using an API tends to be easiest since you can generate a new email address for each test and use a blocking API call to wait for the email to arrive.
How do I automate OTP in Selenium Java?
Use a unique email address (per test) for filling out the sign-up form, use your email-reading API to wait for the email to arrive, extract the OTP from the email’s plain-text content (Pattern.compile("\\b\\d{6}\\b") matches a six-digit code), and use sendKeys to fill in the OTP form field. (This is essentially what our TestInbox.code() method does.)
Do I still need to download ChromeDriver?
As of Selenium 4.6, Selenium Manager downloads a driver for you the first time you run your tests that’s compatible with your installed Chrome. If you have an existing chromedriver on your PATH Selenium will still use it, so get rid of that!
How do I wait for an email without Thread.sleep?
Since testmail.app’s API supports long polling using the livequery=true query parameter we can wait on the server for the email to arrive. The request won’t return until the email arrives. Java’s HttpClient follows redirects so we don’t need to do anything special to handle the 307 responses that are periodically re-issued by the API while waiting for the email. The total amount of time to wait is capped using JUnit’s @Timeout annotation.
Can I run Selenium email tests in parallel?
Yes, you can make your Selenium email tests run in parallel as long as each test uses a different email address and has its own WebDriver object (make sure it’s an instance field and not static). Parallel test execution can be enabled in JUnit via configuration.
Does this work with TestNG?
TestInbox doesn’t depend on JUnit. If you’re using TestNG, you can change @BeforeEach and @AfterEach to @BeforeMethod and @AfterMethod, and use TestNG’s @Test(timeOut = 120_000) in place of JUnit’s @Test and @Timeout(120).
Try it: sign up for testmail.app for free to get your own namespace and API key, export them, and run mvn test -Dtest=SignupEmailTest.
