Mailtrap Blog

How to Automate Email Verification in Selenium

Selenium is a popular open-source tool for automating software testing. With the Selenium WebDriver, you can test web applications across diverse platforms and browsers. Selenium tests can be written in various programming languages, including Java, JavaScript, PHP, Python, and Ruby. 

The Selenium WebDriver allows you to verify the performance of web applications; that is, to test if they work as expected. Instead of testing the functionalities manually, you can use the tool to enhance the efficiency of the process.

In this tutorial, we’re going to see how to automate email verification in Selenium using the Java programming language. We’ll aim to validate if an email has been received by using Selenium to extract some text from the delivered message, automatically.

So, let’s get going…

Prerequisites

Here are the resources we’ll need in this project:

Setting Up Our Project

To set up the Selenium WebDriver with the Eclipse IDE, we’ll start by creating a new project via File > New > Java Project options, and naming it as “SeleniumTutorial”.

Then, a new Java project will be created with the following directories:

To create a new Class file, we’ll right-click on the “src” folder, select New > Class, and name it as “TestEmail”. This class will contain the coding logic for using Selenium for email validation.

Next, to add the Selenium jar files to our project, we’ll right-click on “SeleniumTutorial” and select Properties > Java Build Path > Libraries > Add External JARs

Here is a screenshot of the directory structure of our “SeleniumTutorial” after adding the Selenium jar files:

After successfully setting up our project, we can now start getting our hands dirty by writing a script that can verify email using Selenium.

Join our newsletterOnly the best content, delivered once a month. Unsubscribe anytime.

Test Emails With Mailtrap and Selenium

Now, we’re going to demonstrate how you can use Selenium to verify if a user has received an email message. So, we’ll use the tool to log into our Mailtrap account automatically and check if the message has been delivered.

Sounds exciting?

We’ve got sending emails in Java, also via the Mailtrap SMTP server, covered in another article.

To begin with, let’s import the following packages that we’ll need in this project:

After importing the necessary packages, let’s create an instance of the Selenium WebDriver and set it to our desired browser. 

Here is the code for a Windows machine:

System.setProperty("webdriver.gecko.driver","C:\\Users\\OPIDI\\Desktop\\File 1\\geckodriver.exe");
		 
WebDriver driver = new FirefoxDriver();

Note that for Linux and other systems, you can reference your file location using single backslashes.

Next, let’s launch a new browser session and provide the Mailtrap’s login URL as its parameter. This way, Firefox will navigate to the specified URL automatically.

driver.get("https://mailtrap.io/signin");

Let’s apply an implicit wait method that enables us to delay the execution by 10 seconds before any exceptions are thrown.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

If we right-click on the Mailtrap’s login form and select the Inspect Element option, we notice that the Email field is created using the <input type=”email”> element. 

Therefore, to locate this HTML element using a Selenium command, we’ll use the Selenium’s WebElement interface. Basically, the WebElement represents an HTML element; it allows us to carry out various operations associated with web page interactions.

So, to identify the HTML element, we’ll call the WebDriver’s findElement() method, which returns the element as a WebElement object. Furthermore, we’ll use an XPath expression to specify the element’s location on the web page.

Here is the code:

WebElement email = driver.findElement(By.xpath("//input[@type='email']"));

Then, to set the value of the email field, we’ll call the sendKeys() method and specify our email address, as its parameter.

email.sendKeys("testemail@gmail.com");	

Similarly, since the password field is created using the <input type=”password”> element, we’ll invoke the Selenium’s WebElement interface and call the sendKeys() method to set its value. 

WebElement password = driver.findElement(By.xpath("//input[@type='password']"));
password.sendKeys("mypassword");

To complete the logging in process, we’ll locate the Log in button and use the click() method to click it. 

driver.findElement(By.xpath("//input[@type='submit']")).click();

Once we’ve successfully logged into the Mailtrap platform, we’ll select Demo inbox and click it so that we can access the email messages in our inbox. 

If we inspect the element’s code, we notice that it’s encapsulated in an <a> tag with a title attribute of “Demo inbox”. So, we’ll pick this value and refer to it. 

Here’s the code:   

driver.findElement(By.xpath("//a[@title='Demo inbox']")).click();

Next, if we inspect the messages in our inbox, we notice that they are contained within an <ul> list tag.

Here is the screenshot:

So, we’ll use the contains() method to look for the list of web elements that contain the text we want. In this case, we want to verify if any of our email messages contain the words “ Here comes an attachment”. 

Furthermore, we’ll use the isEmpty() method to validate whether the text has been found or not. In other words, this method will return true if no matching text is found in the email addresses; otherwise, it returns false. 

Consequently, we’ll output the results of the Selenium script for email validation on the Eclipse console.

Here is the code:

List<WebElement> allMessages = driver.findElements(By.xpath("//*[contains(text(), 'Here comes an attachment')]"));      
	 
	      if(allMessages.isEmpty()) {
	    	  System.out.println("Test not passed");
	      }else {
	    	  System.out.println("Test passed");
	      }

Lastly, we’ll close the Firefox browser associated with the WebDriver.

driver.close();

Try Mailtrap For Free

Wrapping Up

Here is the entire code for this tutorial on how to verify email using Selenium:


import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestEmail {

    public static void main(String[] args) {
   	 
   	  //create a Selenium WebDriver instance
   	  System.setProperty("webdriver.gecko.driver","C:\\Users\\OPIDI\\Desktop\\File 1\\geckodriver.exe");
   	 
   	  WebDriver driver = new FirefoxDriver();
     	 
      	//launch the Firefox browser and navigate to the website
      	driver.get("https://mailtrap.io/signin");
     	 
      	//puts an implicit wait for 10 seconds before throwing exceptions     	 
      	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     	 
      	//locate the email field
      	WebElement email = driver.findElement(By.xpath("//input[@type='email']"));
     	 
      	//set the field's value     	 
      	email.sendKeys("myusername@gmail.com");     	 
        	 
      	//locate the password field
      	WebElement password = driver.findElement(By.xpath("//input[@type='password']"));    
     	 
      	//set the password's value
      	password.sendKeys("password");
     	 
      	//locate and click the submit button     	 
      	driver.findElement(By.xpath("//input[@type='submit']")).click();
     	 
      	//locate Demo Inbox and click it
      	driver.findElement(By.xpath("//a[@title='Demo inbox']")).click();
     	 
      	//look for the given text in the list of web elements   					 
      	List<WebElement> allMessages = driver.findElements(By.xpath("//*[contains(text(), 'Here comes an attachment')]"));
     	 
      	//check if text has been found or not     	 
      	if(allMessages.isEmpty()) {
   		   System.out.println("Test not passed");
      	}else {
   		   System.out.println("Test passed");
      	}
     	 
    	//close the Firefox browser.
      	driver.close();    	 


    }

}

If we run the above code, this is what we get on the console:

It worked!

Conclusion

That’s how to automate email verification in Selenium. With Selenium, you can access the contents of the delivered messages and extract some texts automatically, which lets you know whether your email application is functioning as desired.

If you want to learn more about how to use Selenium to automate web tests, you can check its official documentation on its website.

Notably, Mailtrap offers you a robust testing platform for validating the functionalities of your emails before distributing them to real users. You should give it a try today!

All the best with your emails. 

Exit mobile version