Read Mails In Java

 


There may arise a case in Test Automation where you need to read an OTP from a Mail inbox or would like to access a URL link provided to you in your registered email account. One easy way to do so would be to directly login to the Mail Account on your Browser and perform Actions to read/write data from the webpage. This could sound easy at first but may get complicated when you tend to create locators to uniquely identify elements on these third-party applications which may even get change dynamically.

But how about if you can directly get to access the Gmail account by using a simple Java library and writing a few lines of code to get through the content in your mailbox. Today we are going to discuss the same, in which we can easily read the Mail subject + body content without directly logging into the application but by doing so through the backend.

Prerequisite Step: The account you are trying to log in must have the Setting "Less secure app access" enabled, which allows accessing your account easily from Java.

Follow the below-written code line by line to create a connection with your Gmail account. As a first step add the dependency javax.mail into your pom.xml



Below is the main code for reading the mail inbox.



Here we will read the Mail Body whose subject is as "Fwd: Please sign the document" which is declared in a variable message in Line:47.

Pass the credentials of your account (email id and password) as variables in Line:45/46

The logic states to read the mail INBOX as given in Line:59. All the mails would be traversed through an array object, starting from the very latest email to the oldest email.

As per Line:80, wherever out expected Mail Subject is matched with the Actual Mail subject, we would step into the if condition to read the Mail Body Part and break out of the loop of reading all mails. 

Other helper methods are used to read and parse the MimeMultipart object to String type object as per the actual content in the mail body.




Voila! It is done, without any hassle to log in to Gmail Account by finding locators and so. You can easily read the content of your mail body along with URL redirection links on your Java console and make use of it by easy String manipulations.

Please drop a comment here, if you wish to get the complete class file of the code. 

Thanks
 









 


Comments

Post a Comment

Popular posts from this blog

Passing Data From the TestNG.xml file to Tests

Demo Click Jack Maropost.Com