This post is dedicated to all the scenarios where we normally need to check the Email verification manually a lot. I’m trying to remove theManual effort of all the QA guys who involved in Email verification from any of the Email account.
Moreover, this also verify that correct Email is received OR Not wrt to the Subject, From, Content in Message body.
Here is the Code to check in Gmail inbox to check :-
========================================================
* Copyright @ QA All rights Reserved.
* CONFIDENTIAL. Use is subject to license terms.
* Description: This piece of code will test the Gmail Account for Email verification with the help of Javax API
* This is the scenario which will be used to test the gmail functionality in the Overall Application
* This Code/Scenario will be able to test if Email received in Gmail with specific Email Address, Subject line, Some search in the Body to Test with in 3 minutes of time.
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FlagTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.SearchTerm;
public class CheckEmail {
/**
* Searches for e-mail messages containing the specified keyword in
* Subject field.
* @param host
* @param port
* @param userName
* @param password
* @param keyword
* @throws IOException
*/
@SuppressWarnings(“unused”)
private boolean textIsHtml = false;
/**
* Return the primary text content of the message.
*/
private String getText(Part p) throws MessagingException,IOException {
if (p.isMimeType(“text/*”)) {
String s = (String)p.getContent();
textIsHtml = p.isMimeType(“text/html”);
return s;
}
if (p.isMimeType(“multipart/alternative”)) {
// prefer html text over plain text
Multipart mp = (Multipart)p.getContent();
String text = null;
for (int i = 0; i < mp.getCount(); i++) {
Part bp = mp.getBodyPart(i);
if (bp.isMimeType(“text/plain”)) {
if (text == null)
text = getText(bp);
continue;
} else if (bp.isMimeType(“text/html”)) {
String s = getText(bp);
if (s != null)
return s;
} else {
return getText(bp);
}
}
return text;
} else if (p.isMimeType(“multipart/*”)) {
Multipart mp = (Multipart)p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i));
if (s != null)
return s;
}
}
return null;
}
public boolean searchEmail(String userName,String password, finalString subjectKeyword, final String fromEmail, final StringbodySearchText) throws IOException {
Properties properties = new Properties();
boolean val = false;
// server setting
properties.put(“mail.imap.port”, 993);
// SSL setting
properties.setProperty(“mail.imap.socketFactory.class”,”javax.net.ssl.SSLSocketFactory”);
properties.setProperty(“mail.imap.socketFactory.fallback”, “false”);
properties.setProperty(“mail.imap.socketFactory.port”,String.valueOf(993));
Session session = Session.getDefaultInstance(properties);
try {
// connects to the message store
Store store = session.getStore(“imap”);
store.connect(userName, password);
System.out.println(“Connected to Email server….”);
// opens the inbox folder
Folder folderInbox = store.getFolder(“INBOX”);
folderInbox.open(Folder.READ_ONLY);
//create a search term for all “unseen” messages
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, true);
//create a search term for all recent messages
Flags recent = new Flags(Flags.Flag.RECENT);
FlagTerm recentFlagTerm = new FlagTerm(recent, false);
SearchTerm searchTerm = new OrTerm(unseenFlagTerm,recentFlagTerm);
// performs search through the folder
Message[] foundMessages = folderInbox.search(searchTerm);
System.out.println(“Total Messages Found :”+foundMessages.length);
for (int i=foundMessages.length-1 ; i>=foundMessages.length-10;i–) {
Message message = foundMessages[i];
Address[] froms = message.getFrom();
String email = froms == null ? null : ((InternetAddress)froms[0]).getAddress();
if(message.getSubject()==null){
continue;
}
Date date = new Date();//Getting Present date from the system
long diff = date.getTime()-message.getReceivedDate().getTime();//Get The difference between two dates
long diffMinutes = diff / (60 * 1000) % 60; //Fetching the difference of minute
// if(diffMinutes>2){
// diffMinutes=2;
// }
System.out.println(“Difference in Minutes b/w present time & Email Recieved time :” +diffMinutes);
try {
if(message.getSubject().contains(subjectKeyword) &&email.equals(fromEmail) && getText(message).contains(bodySearchText) && diffMinutes<=3){
String subject = message.getSubject();
// System.out.println(getText(message));
System.out.println(“Found message #” + i + “: “);
System.out.println(“At “+ i + ” :”+ “Subject:”+ subject);
System.out.println(“From: “+ email +” on : “+message.getReceivedDate());
if(getText(message).contains(bodySearchText)== true){
System.out.println(“Message contains the search text “+bodySearchText);
val=true;
}
else{
val=false;
}
break;
}
} catch (NullPointerException expected) {
// TODO Auto-generated catch block
expected.printStackTrace();
}
System.out.println(“Searching.…” +”At “+ i );
}
// disconnect
folderInbox.close(false);
store.close();
} catch (NoSuchProviderException ex) {
System.out.println(“No provider.”);
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println(“Could not connect to the message store.”);
ex.printStackTrace();
}
return val;
}
/**
* Test this program with a Gmail’s account
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String password = “passwrd”;
CheckEmail searcher = new CheckEmail();
String subjectKeyword = “New Registration – Successful”;
String bodySearchText =”You have successfully register to our services”;
searcher.searchEmail(userName, password,subjectKeyword,fromEmail, bodySearchText);
}
}
Hi vishvas,
Your idea is good and you have written program very well but if we have some mechanism for password getting it from some file and get it encrypted in the code that would be good rather than simply giving directly the password in the code. becoz third person can see the password directly..
This is just my view point I think if the password encryption is also done then its really perfect…
Hi RamKrishna,
Thanks for your valuabel feedback.
This was actually done intentially, Yes it would be a great idea to have encryption OR having credential in some other file.
Scenarios was keeping in mind that If any one wants to modify the same for OUTLOOK or some Other Email account, He/she can easily configured the same.
Morover, If some one has BDD or Managemnt level test case just like below, he/she can easily used it as :-
Check gmail account for Email Recived:
# Check Gmail for Verification with User “gurutester1@gmail.com” and password “p488w0rd” : Here can make the calling of account whichever feasible for the user
#Search for subjectKeyword “New User registered” fromEmail “web@google.com” bodySearchText “You have successfully register ”
Hope, this will help you guys. Thanks..!!
–Vishwas
Great Work Vishwas. Very Well Explained!!
I just had a few questions. Will the same code work for Outlook?
I have a scenario where i upload a file on the application and as soon as the file is uploaded, the uploader receives an email into outlook.
So it is possible to test the same with the above code?
Also i wanted to know if Javax API free?
Regards,
Shruti
Thank you
My account sharsh
My account
Great Work Vishwas. Very Well Explained!!
I just had a few questions. Will the same code work for Outlook?
I have a scenario where i upload a file on the application and as soon as the file is uploaded, the uploader receives an email into outlook.
So it is possible to test the same with the above code?
Also i wanted to know if Javax API free?
Regards,
Hello,
DO Javax api and java mail both are diffrent are same,
I have used the same code as above and I ma getting the message as invalid credentials though I have given valid credentials.
Could you please guide anybody what are the jars I need to be imported. and preconfigurations required.
http://www.oracle.com/technetwork/java/javamail/index.html
Follow this link to read more about mail api
Hi Vishwas:
I’m trying to extract a specific text received from an Email sent after ending a flow. I need to fetch a code sent by Email to my Gmail account, but I’m not able to reach the xpath:
87884
The error is the next:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {“method”:”xpath”,”selector”:”//*[@id=”:13s”]/div[1]/div[2]/div[1]/div[1]/div[6]”}
I can’t reach the element with xpath, id… No way!!!
Could you please help me?
Thanks for contacting.
Could you please share which xpath you are trying to find for the same please share some snapshot.
Thanks
Dwarika
What Part p in the getText method ?