Skip to main content

Verify email confirmation using Selenium WebDriver

Note: If you are new to java and selenium then start with selenium java training videos. 



How to Verify Email Confirmation Using Selenium 4 and JavaMail (2026 Guide)

Email confirmation is a critical part of most registration flows — account activation, password reset, multi-factor authentication, and onboarding.

Every automation engineer eventually faces the same challenge: How do you verify an email confirmation link inside a Selenium test without making it slow and flaky?

The wrong instinct is to automate Gmail's UI with Selenium. It's fragile, slow, and breaks constantly. The right approach:

  1. Use Selenium for browser automation
  2. Use JavaMail (IMAP) to read the email directly
  3. Extract the confirmation link
  4. Continue the test in Selenium

Why Not Automate Gmail UI With Selenium?

Automating the Gmail UI means logging in, searching, clicking a message, and parsing content from a third-party interface that changes frequently. This leads to:

  • Flaky, slow tests
  • Tight coupling to an external UI
  • Authentication headaches (2FA, CAPTCHAs)

Reading the mailbox directly via IMAP is cleaner, faster, and more reliable.

Modern Requirements

⚠️ Gmail no longer supports simple username/password authentication for IMAP.

You must:

  1. Enable 2-Step Verification on your Gmail account
  2. Generate a Gmail App Password
  3. Use that App Password for IMAP access
  4. Store credentials in environment variables or CI secrets — never in code

Maven Dependencies

<!-- JavaMail -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

<!-- HTML email parsing -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.17.2</version>
</dependency>

Step 1: Email Helper Class (IMAP Polling)

import jakarta.mail.*;
import jakarta.mail.search.SubjectTerm;
import java.util.Properties;

public class EmailHelper {

    public static Message waitForEmail(String subject, int timeoutSeconds) throws Exception {
        String host = "imap.gmail.com";
        String username = System.getenv("TEST_EMAIL_USER");
        String password = System.getenv("TEST_EMAIL_PASS");

        Properties properties = new Properties();
        properties.put("mail.store.protocol", "imaps");

        Session session = Session.getInstance(properties);
        Store store = session.getStore("imaps");
        store.connect(host, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

        int waited = 0;
        while (waited < timeoutSeconds) {
            Message[] messages = inbox.search(new SubjectTerm(subject));
            if (messages.length > 0) {
                return messages[messages.length - 1];
            }
            Thread.sleep(5000);
            waited += 5;
        }

        throw new RuntimeException("No email found with subject: " + subject);
    }
}

Key design decisions:

  • Polls every 5 seconds rather than using a hard-coded sleep
  • Returns the latest matching message to avoid stale results
  • Credentials loaded from environment variables

Step 2: Extract the Confirmation Link

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class EmailParser {

    public static String extractConfirmationLink(Message message) throws Exception {
        String content = message.getContent().toString();
        Document document = Jsoup.parse(content);
        Element link = document.select("a").first();

        if (link == null) {
            throw new RuntimeException("No confirmation link found in email.");
        }

        return link.attr("href");
    }
}

💡 Tip: If your email contains multiple links, use a more specific CSS selector — e.g., a[href*="confirm"] — to avoid grabbing the wrong one.

Step 3: Wire It Together in Selenium 4

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class EmailVerificationTest {

    public static void main(String[] args) throws Exception {
        Message message = EmailHelper.waitForEmail("Welcome to My Application", 60);
        String confirmationUrl = EmailParser.extractConfirmationLink(message);

        WebDriver driver = new ChromeDriver();
        driver.get(confirmationUrl);

        System.out.println("Registration page loaded: " + driver.getTitle());
        driver.quit();
    }
}

The full test flow:

  1. Register user
  2. Poll inbox for confirmation email
  3. Extract link
  4. Open link in browser
  5. Continue validation

Handling Email Delivery Delays

Do: Poll with a timeout, fail with a clear error message, search by subject or unique token, delete/mark email after use.

Avoid: Thread.sleep(30000), silent failures, grabbing the first available email, leaving stale emails that cause false positives.

CI/CD Considerations

  • Store email credentials as pipeline secrets
  • Use a dedicated test mailbox — not a personal account
  • Clean the inbox regularly to avoid false positives from old emails
  • Scope searches by date to avoid matching stale messages

Better Alternative: Fake SMTP Servers

For non-production environments, skip Gmail entirely and use a local mail capture tool:

  • MailHog — great for local dev and Docker setups
  • GreenMail — integrates directly with JUnit tests

These capture outgoing emails with no external dependency — the preferred approach for enterprise test automation.

Summary

Wrong WayRight Way
Automate Gmail UIRead inbox via IMAP
Hard-coded sleepsPoll with timeout
Hardcoded credentialsEnvironment variables
String splittingJsoup HTML parsing
Coupled email + Selenium logicSeparate helper classes

Following this pattern keeps your automation framework clean, reliable, and easy to maintain.

Comments

  1. Great post, thanks for sharing. Also maybe we could get a link to a straight text file as the blogger doesn't allow for us to copy the code you posted to test it out.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. You should be able to copy now, let me know if you are not

    ReplyDelete
  4. Thanks to Steve for identifying a problem with code, I have corrected it now

    ReplyDelete
  5. To be honest I do not agree. We use gmail box to store our confirmation emails. We have a class that lets us log in to gmail and access the last message, which you can then parse to find links, texts, images, etc. It's a simple class, just a few lines of code so I wouldn't say it's not clean. Moreover in this way we don't need any custom reporting (we can use our default reporting system for Selenium).

    However I can see one advantage of your solution. If you use POP3 then it's much simpler to switch between mailboxes (if one day you decide you cannot use gmail for any reason). Also this way probably is a little bit faster too.

    ReplyDelete
  6. Interesting post. Thank you!

    ReplyDelete
  7. Not able to copy the code... :(

    ReplyDelete
    Replies
    1. You can use ViewRaw link to copy code or use this - https://gist.github.com/1558421#file_seemailverify.java

      Delete
  8. This is really a great post.
    But when I need to check mails, I do not have username and password. Just need to verify if email workflow is being fired or not through SharePoint. Can you please help?

    ReplyDelete
    Replies
    1. In that case you may have to check on your SMTP server about email being fired

      Delete
  9. hi,
    is there any way to assert mail template using selenium?

    ReplyDelete
    Replies
    1. Could you elaborate more on your question?

      Delete

Post a Comment

No spam only genuine comments :)

Popular posts from this blog

Using xPath to reach parent of an element

Note: If you are new to java and selenium then start with selenium java training videos .   I generally prefer CSS selectors over XPath when writing Selenium locators. CSS selectors are concise, readable, and usually provide everything I need. However, there are situations where XPath is a better fit—particularly when I need to navigate through an element's hierarchy, such as moving from an element to its parent, grandparent, or sibling. This post shows one such real-world example. The Problem I came across a situation where I needed to click a link based on the value of an input field. The HTML structure contained multiple similar groups of elements. The input field and the link I wanted to click were not directly related, but they shared a common parent structure. In the following example above, the input element is highlighted, and I need to click the corresponding anchor ( <a> ) element . The challenge is that there may be multiple similar structures on the page. I th...

Real Time JMeter Result Using Backend Listener

Since JMeter 2.13 Backend Listener has been available to create real time graph of JMeter Test. Following tutorial explain the entire process in detail. At the end of this tutorial you would be able to create JMeter Live Test Result dashboard similar to following - This tutorial borrows information from many sources and my own experiments with JMeter live reporting dashboard. I have added source of information wherever applicable But before we can build such a snazzy JMeter Live Reporting dashboard we need to understand two more components - influxDB (a time series database) and Grafana Dashboard This is a big tutorial, so take deep breath :-) and follow on. Once you complete set up specified in this tutorial then you can watch JMeter Training Video Tutorial to watch this in action. What is Time Series Database? A time series is a sequence of data points , typically consisting of successive measurements made over a time interval . Examples of time ...