How to Automate Email Verification in Selenium

On March 31, 2020
9min read
Aleksandr Varnin Full Stack Developer @ Railsware

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.

We’ll also show you how to run the automation with Mailtrap API. When advanced protection is enabled for Mailtrap’s sign-in page (reCAPTCHA), we block bots, so UI testing with Selenium WebDriver won’t work. But if you set it up via API, there won’t be any problems, even with the advanced protection.  

So, let’s get going…

Prerequisites

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

  • Mailtrap – if you haven’t yet, you’ll need to register to access our pre-production testing environment. There, you’ll get your SMTP credentials, which you can use in your development environment to test emails. 
  • Java Development Kit (JDK) – you can download and install it from here.
  • Eclipse IDE – you can download and install it from here. Remember that you can also use any other Java IDE of your choice.
  • Selenium WebDriver – you can download the Selenium Client and WebDriver for Java from the Selenium official website here. After creating a project in Eclipse, we’ll add the downloaded Selenium jar files via the Java Build Path option. 
  • Driver executable – based on the browser you’ll use for executing your Selenium script for email validation, you can download its respective driver executable from here

If you’re using the API method, you’ll also need the following resources

  • AsyncHttpClient – download and install the packages from here to make the API calls.
  • JSON in Java –  use this MVN repository to parse the API calls response 

Aside from the above, you can also use the libraries listed in the screenshot below to create an automated testing app. 

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.

Test Emails With Mailtrap and Selenium

Reminder: UI testing with Selenium WebDriver doesn’t work with advanced sign-up protection. Please use our API instead. 

On that note, we’re going to demonstrate how you can use Selenium to verify if a user has received an email message, assuming the advanced protection is off. 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:

  • org.openqa.selenium.* – this package allows us to access the Selenium capabilities for automating web tests. 
  • org.openqa.selenium.firefox.FirefoxDriver – this package has the FirefoxDriver class required to initialize a Firefox-focused driver onto the browser that the WebDriver class has instantiated. If you’re using another web browser, which is not Firefox, you can import its driver server according to the instructions on the Selenium official website referenced previously.
  • java.util.List – since the email messages in the Mailtrap platform are contained within an unordered list element, we’ll use this Java interface to access them.
  • java.util.concurrent.TimeUnit – we’ll use this Java interface to specify a time duration before the execution of our code. 

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("/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

Testing Automation with Mailtrap API

As mentioned earlier in this tutorial, using Mailtrap API for this automation is the way to go with advanced protection. Below are the references for API calls, and we’ll show you how to render a specific email in HTML. 

Sign in with Mailtrap API token

Grab the API token and use it for calls. You can find or create your token under Settings > API Tokens, as shown in the image below. You’ll also need the Account ID, located under Settings > Account Settings.  

With that, you’ll need to copy your API Token to the Selenium WebDriver to run automated testing. Keep in mind that the token with an Inbox Viewer or higher permissions. In this example, we’re using Inbox Viewer permission since you’ll be just reading messages.  

Check all messages

The API call below allows you to get all messages for a certain inbox. 

/api/accounts/{account_id}/inboxes/{inbox_id}

Check one message

Grab the message ID and make the API call below to get information for a specific message. Aside from verifying an email, you can get other information with this call – SMTP info, for example. 

/api/accounts/{account_id}/inboxes/{inbox_id}/messages/{message_id}

Render the message in a browser

From the response of the API call above, there is an HTML path. Check the snippet below as an example, and here’s the link to this call:

/api/accounts/{account_id}/inboxes/{inbox_id}/messages/{message_id}/body.html

If you use the link in the response, you’ll be able to see the HTML version of the email for this instance. Aside from that, you could also inspect other email formats, e.g. HTML source, Text, and EML. 

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("/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!

API Method

To stress, the code above works without advanced protection. If the advanced protection is on (e.g. reCAPTCHA), please use Mailtrap API as shown above. And here’s the entire code for the API method:

public class TestEmail {
	public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
		final String apiToken = "140cbadffe14b6a85d2f7a4f0b93b3b1";
		final String accountId = "1397131";
		final String host = "https://mailtrap.io";
		final String testNotPassed = "Test not passed";
      	
		
		// initialize client for API calls
      	AsyncHttpClient client = new DefaultAsyncHttpClient();
      	
      	// get all inboxes for the account
      	Response inboxesResponse = client.prepare("GET", mailtrap + "/api/accounts/" + accountId + "/inboxes/")
      	  .setHeader("Content-Type", "application/json")
      	  .setHeader("Api-Token", apiToken)
      	  .execute()
      	  .get();
      	
      	if (inboxesResponse.getStatusCode() != 200) {
		   System.out.println("Cannot find inboxes for the account");
		   System.out.println(testNotPassed);
		   System.exit(0);
	   	}
      	
      	String inboxesResponseBody = inboxesResponse.getResponseBody();
      	JSONArray inboxes = new JSONArray(inboxesResponseBody);
      	
      	// get first inbox
      	String inboxId = inboxes.getJSONObject(0).getBigInteger("id").toString();
      	
      	// get messages from first inbox
		Response inboxMessagesResponse = client.prepare("GET", mailtrap + "/api/accounts/" + accountId + "/inboxes/" + inboxId + "/messages/")
      	  .setHeader("Content-Type", "application/json")
      	  .setHeader("Api-Token", apiToken)
      	  .execute()
      	  .get();
		
		if (inboxesResponse.getStatusCode() != 200) {
		   System.out.println("Cannot find inbox " + inboxId);
		   System.out.println(testNotPassed);
		   System.exit(0);
	   	}
		
		String inboxMessagesResponseBody = inboxMessagesResponse.getResponseBody();
		JSONArray messages = new JSONArray(inboxMessagesResponseBody);
		
		// get first message
		String messageId = messages.getJSONObject(0).getBigInteger("id").toString();
		String messageHtmlPath = messages.getJSONObject(0).getString("html_path");
		
		Response messagesResponse = client.prepare("GET", mailtrap + messageHtmlPath)
		      	  .setHeader("Content-Type", "application/json")
		      	  .setHeader("Api-Token", apiToken)
		      	  .execute()
		      	  .get();
		
		if (messagesResponse.getStatusCode() != 200) {
		   System.out.println("Cannot find message " + messageId);
		   System.out.println(testNotPassed);
		   System.exit(0);
	   	}
		String messagesResponseBody = messagesResponse.getResponseBody();
		
		client.close();

      	System.setProperty("webdriver.gecko.driver", "/Users/exampleusertest/geckodriver");
        // create a Selenium WebDriver instance
		WebDriver driver = new FirefoxDriver();
      	//launch the Firefox browser and navigate to the HTML version of the email
      	driver.get(mailtrap + messageHtmlPath + "?api_token=" + apiToken);
      	//puts an implicit wait for 10 seconds before throwing exceptions
      	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      	
      	Boolean htmlDisplayed = driver.findElement(By.xpath("//*[contains(text(), 'Congrats for sending test email with Mailtrap!')]")).isDisplayed();
      	
      	if(htmlDisplayed) {
      		System.out.println("HTML of email is displayed. Test passed");
		   
	   	} else {
	   		System.out.println(testNotPassed);
	   	}
	 	//close the Firefox browser.
	   	driver.close();
	}
}

If you run the code above, this is the response you get. 

Again, 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.

Alternatively, learn how you can easily test various user scenarios with a ready to use integration of Kakunin (E2E testing framework) + Mailtrap from our case study with The Software House.

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. 

Article by Aleksandr Varnin Full Stack Developer @ Railsware

Comments

2 replies

dipti

this blog is very helpful for beginners it is very great information thanks for sharing keep posting

s kumar

many error / not good example for VB.NET Selenium

1 : how to hide command prompt in vb.net ( VB 2019 )

2 SendKey Ctrl V not Work in OpenQA.Selenium.Chrome

3 Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5) not good work in VB.net

4 ExecuteAsyncScript not work Fast or not get any Error in

Try

Catch ex As Exception

End Try

5 Selenium.Chrome , i think this is good work in C or C or C# , VB.net code not on any web side

6 Selenium.Chrome is good tools but not usefull for VB.NET developer

share new code with me soft.developer2k[a]gmail.com

Comments are closed.