Article featured image
Automated email testing with Selenium and Java
6min readLast updated: March 12, 2025

Selenium is a powerful tool for automating web-based application testing, making it ideal for validating user interactions like clicks, form submissions, and navigation. Its support for multiple browsers (Chrome, Firefox, Safari, Edge) and programming languages (Java, Python, C#, JavaScript) offers flexibility and broad compatibility.

Selenium integrates smoothly with testing frameworks like TestNG and JUnit, as well as CI/CD pipelines, enabling efficient and continuous testing. Being open-source, it’s cost-effective and highly customizable. Selenium is best suited for UI and regression testing but is less effective for non-web applications or performance testing.

In this tutorial, we’ll automate email verification using Selenium in Java. We’ll check if an email was received and extract the verification code. Additionally, we’ll show how Testmail’s API can simplify the process.

Prerequisites

Java Development Kit (JDK): Install the latest version of the Java Development Kit (JDK) from Oracle JDK or OpenJDK.

Maven or Gradle: Use Maven or Gradle for managing project dependencies. An IDE like IntelliJ IDEA or Eclipse is also recommended for coding and running Java projects.

Google Chrome Browser & ChromeDriver: Install Google Chrome and download the matching version of ChromeDriver. Add ChromeDriver to your system’s PATH to enable Selenium to control the browser.

testmail.app account: Sign up at testmail.app and retrieve your API key and namespace from the dashboard. This key will be used to interact with testmail.app’s API for email verification.

testmail.app offers two APIs: a simple JSON API and a full-featured GraphQL API (see the comparison table).

For this tutorial, we will use the JSON API.

The JSON API is straightforward and works in any environment using HTTP GET requests. Only two parameters are mandatory:

  • &apikey=YOUR_APIKEY
  • &namespace=YOUR_NAMESPACE

To make the output more readable in your browser, add &pretty=true.

When waiting for new emails, you can use the &livequery=true parameter to enable "live" queries. This feature allows the API to wait until at least one matching email is found before returning a result. If a match is found, the result is returned immediately. If no match is found within a minute, the API responds with an HTTP 307 redirect, prompting your HTTP client to resend the query. This process continues indefinitely, so it's important to set a timeout in your testing suite to avoid endless waiting.

Test emails with Selenium and testmail.app

Set up dependencies

Add these dependencies to your pom.xml, here we are using Maven.

<?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 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example</groupId>
    <artifactId>java-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <!-- Selenium WebDriver -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.4.0</version>
        </dependency>
        
        <!-- Apache HttpClient for API calls -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.2</version>
            <scope>test</scope>
        </dependency>
        
        <!-- Jackson for JSON parsing -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.3</version>
        </dependency>
    </dependencies>
</project>

pom.xml

Run the following Maven command to download dependencies:

mvn clean install

Generate a test email address

You will need to use Testmail's API to create a temporary email address. For simplicity, we'll create the email dynamically in your Java code:

import java.util.UUID;

public class TestmailUtils {
    private static final String NAMESPACE = "YOUR_NAMESPACE";
    public static String generateEmail() {
        String inboxName = NAMESPACE+".test-" + UUID.randomUUID().toString();
        return inboxName + "@inbox.testmail.app";
    }
}

TestmailUtils.java

You can call this function whenever you need a new email address for testing.

Automate signup with Selenium

Navigate to the signup page and fill in the form using Selenium WebDriver:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.By;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

public class SignupTest {
    private WebDriver driver;
    
    @BeforeEach
    void setUp() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--disable-web-security");
        options.addArguments("--remote-allow-origins=*");
        
        driver = new ChromeDriver(options);
    }
    
    @Test
    void testSignup() {
        // Navigate to the Testmail signup page
        driver.get("http://yourdomain/login");

        // Generate the test email
        String testEmail = TestmailUtils.generateEmail();
        String name = "John";

        // Find the email, first name, and last name fields and input the generated data
        WebElement emailField = driver.findElement(By.id("email"));
        emailField.sendKeys(testEmail);

        WebElement nameField = driver.findElement(By.id("name"));
        nameField.sendKeys(name);

        // Find the signup button and submit the form
        WebElement signupButton = driver.findElement(By.id("login-with-email"));
        signupButton.click();
        
        OTPVerification.verifyOTP(driver);
    }
    
    @AfterEach
    void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

SignupTest.java

Verify email delivery with testmail.app API

We will now use the API to check if the OTP email has been received at the generated email address.

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.jupiter.api.Assertions.fail;

public class EmailVerifierTest {
    private static final String API_KEY = "YOUR_API_KEY";
    private static final String NAMESPACE = "YOUR_NAMESPACE";
    
    public static JsonNode fetchInbox() {
        String url = "https://api.testmail.app/api/json?apikey=" + API_KEY + "&namespace=" + NAMESPACE;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(request);
            String jsonResponse = EntityUtils.toString(response.getEntity());

            ObjectMapper mapper = new ObjectMapper();
            return mapper.readTree(jsonResponse);
        } catch (Exception e) {
            e.printStackTrace();
            fail("Failed to fetch inbox");
        }
    }
}

EmailVerifierTest.java

This function will query for emails sent to the temporary address and return the email details as JSON.

Extract the OTP

Once you receive the email data, parse the OTP code from the body and use it for the next step of the verification process.

import com.fasterxml.jackson.databind.JsonNode;

public class OTPExtractor {
    public static String extractOTP(JsonNode inbox) {
        JsonNode email = inbox.get("emails").get(0); // Get the first email in the inbox
        String emailBody = email.get("html").asText();

        // Assuming the OTP is alphanumeric
        String otp = emailBody.replaceAll("[^A-Za-z0-9]", ""); // Extract alphanumeric characters
        return otp;
    }
}

OTPExtractor.java

This function searches for digits in the email body (you may need to adjust the regex or the extraction method depending on the email content format).

Automate OTP entry using Selenium

Finally, use Selenium to input the OTP into the signup form and complete the registration process:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.openqa.selenium.chrome.ChromeOptions;

public class OTPVerification {

   public static void verifyOTP(WebDriver driver) {
        JsonNode inbox = EmailVerifierTest.fetchInbox();
        String otpCode = OTPExtractor.extractOTP(inbox);

        // Find the OTP input field and enter the OTP
        WebElement otpField = driver.findElement(By.id("verify-email"));
        otpField.sendKeys(otpCode);

        // Submit the OTP form
        WebElement verifyButton = driver.findElement(By.id("verify-code"));
        verifyButton.click();
    }
}

OTPVerification.java

Now run the following maven command to run the test:

mvn test

The following output will be shown in the terminal:

Subscribe to blog

Stay updated with our latest insights and curated articles delivered straight to your inbox.