Open Gmail inbox and get the unread mails count using Selenium Webdriver

0 votes
Anyone please suggest how to automate opening gmail inbox and getting a count of unread mails using Selenium Webdriver?
May 20, 2019 in Selenium by Naitik
7,267 views

1 answer to this question.

0 votes

Hi Naitik, you can follow this piece of code to achieve this type of automation using Selenium Webdriver:

System.setProperty("webdriver.chrome.driver", C:\\Users\\Abha_Rathour\\Downloads\\ExtractedFiles\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

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

driver.get("https://gmail.com/");

driver.findElement(By.id("identifierId")).sendKeys("email_id");

driver.findElement(By.className("CwaK9")).click();   // Identifier for Next button

driver.findElement(By.xpath("//*[@id=\"password\"]/div[1]/div/div[1]/input")).sendKeys("password");

driver.findElement(By.className("CwaK9")).click();   // Identifier for Next button

// Get title of the current page
System.out.println("Title of Page: " + driver.getTitle());
// List of all Unread Emails
List<WebElement> unreademail = driver.findElements(By.className("zE"));
// Display count of unread emails
System.out.println("Total No. of Unread Mails: " + unreademail.size());
answered May 21, 2019 by Abha
• 28,140 points
public static void ReadGMailMessageBody(String username,String password) throws MessagingException, IOException{

try{

Properties properties = new Properties();

properties.setProperty("mail.store.protocol", "imaps");

Session emailSession =  Session.getDefaultInstance(properties);

Store emailstore = emailSession.getStore("imaps");

emailstore.connect("smtp.gmail.com","xyz@gmail.com","password");

//getting Inbox Folder

System.out.println("Email connection done");

Folder emailFolder =  emailstore.getFolder("INBOX");

emailFolder.open(Folder.READ_ONLY);

Message messages[] = emailFolder.getMessages();

String result = "";

for(int i = messages.length;i>=messages.length-4;i--){

System.out.println("Inbox box email count: "+ messages.length);

Message message = messages[i];

System.out.println(message.getSubject());

if( message.getSubject().contains("example:specific character from the email body")){

MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

result = getTextFromMimeMultipart(mimeMultipart);

System.out.println(result );

break;

}

}

emailFolder.close(false);

emailstore.close();

}

catch(NoSuchProviderException nspe){

}catch(MessagingException  me){

me.printStackTrace();

}

}

private static String getTextFromMimeMultipart(

        MimeMultipart mimeMultipart)  throws MessagingException, IOException{

    String result = "";

    int count = mimeMultipart.getCount();

    for (int i = 0; i < count; i++) {

        BodyPart bodyPart = mimeMultipart.getBodyPart(i);

        if (bodyPart.isMimeType("text/plain")) {

            result = result + "\n" + bodyPart.getContent();

            break; // without break same text appears twice in my tests

        } else if (bodyPart.isMimeType("text/html")) {

            String html = (String) bodyPart.getContent();

            result = result + "\n" + org.jsoup.Jsoup.parse(html).text();

        } else if (bodyPart.getContent() instanceof MimeMultipart){

            result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());

        }

    }

    return result;

}

public List<String> getUrlsFromMessage(Message message, String linkText) throws Exception{

    String html = getMessageContent(message);

    List<String> allMatches = new ArrayList<String>();

    Matcher matcher = Pattern.compile("(<a [^>]+>)"+linkText+"</a>").matcher(html);

    while (matcher.find()) {

      String aTag = matcher.group(1);

      allMatches.add(aTag.substring(aTag.indexOf("http"), aTag.indexOf("\">")));

    }

    return allMatches;

  }

public String getMessageContent(Message message) throws Exception {

    StringBuilder builder = new StringBuilder();

    BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));

    String line;

    while ((line = reader.readLine()) != null) {

      builder.append(line);

    }

    return builder.toString();

  }
Hey @Faizal, did this code work for you?

Related Questions In Selenium

0 votes
2 answers

Is there any way to get the text of a web element using Selenium Webdriver?

use gettext() in java : string lableText = ...READ MORE

answered Sep 3, 2020 in Selenium by Sri
• 3,190 points
8,508 views
0 votes
1 answer

How to get the select options using Selenium WebDriver in Java

Hey there! You should be able to get ...READ MORE

answered Jun 14, 2019 in Selenium by Surya
• 970 points
4,769 views
0 votes
2 answers

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,500 points
13,767 views
0 votes
2 answers

Problem while using InternetExplorerDriver in Selenium WebDriver

enable trusted connection  in internet explorer by ...READ MORE

answered Aug 31, 2020 in Selenium by Sri
• 3,190 points
9,186 views
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,910 points
7,261 views
0 votes
2 answers

How to use such xpath to find web elements

xpath are two types. 1) Absolute XPath:    /html/b ...READ MORE

answered Sep 3, 2020 in Selenium by Sri
• 3,190 points
7,900 views
+1 vote
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP