When you build a test framework using Java to read emails, connecting to the Gmail inbox becomes necessary by enabling Two-factor authentication and creating a secure app password that you can use in the code. The solution that you build to read emails works locally but does not work in cloud.
How you can make it work, please follow the following steps:
1- Go to your account settings and then click the Security tab.
2- Enable the 2-Step verification option.

3- Generate the password, it’s a 12 word auto generated secure password. Copy it and save somewhere.

4- Now use the following code to access your inbox.
public static void check(String subject, String toEmailAddress) throws MessagingException, IOException, InterruptedException {
String host = "imap.gmail.com";
String user = "testaccount@gmail.com";
String password = "SECUREPASSWORD";
// create properties
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.starttls.enable", "true");
properties.put("mail.imap.ssl.trust", host);
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imaps");
store.connect(host, user, password);
// retrieve the messages from the folder in an array and print it
Folder inbox;
boolean found=false;
int j = 1;
// This loop will help you to keep on accessing your inbox to check the email arrival in your inbox
do {
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
message.setFlag(Flag.SEEN, true);
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
InternetAddress recipient = (InternetAddress) message.getRecipients(Message.RecipientType.TO)[0];
if (message.getSubject().contains(subject) && recipient.getAddress().equals(toEmailAddress)) {
System.out.println("rif found");
found=true;
System.out.println(getBestaetigenLink(message));
break;
}
}
j++;
Thread.sleep(5000);
}
while (j <= 10 & !found);
inbox.close(false);
store.close();
}
Now call this function inside your test like:
check("EMAIL Expected Subject", "RecipienetEmail@gmail.com");
I hope this article will save your time. Please leave a comment if this solution has helped you.