How to click on a Particular email from gmail inbox in Selenium?

我们两清 提交于 2021-02-07 04:40:25

问题


I hv to click on a particular email, in that case what should I do? I seen there is a Webtable with multiple indexes, I hv to select 1 & click on it. does anyone have code how to handle webTables in WebDriver? See exact situation in below screen- http://screencast.com/t/XRbXQVygNkN6

I was trying with below code -Plz suggest me for rest of the action.

After gmail Login-

1st Ihv clicked on inbox link--->>then Promotions--->>then I hv to click on particular email

WebElement PromotionsSection =driver.findElement(By.xpath("//div[contains(@id,':2y')]"));
PromotionsSection.click();

WebElement email=driver.findElement(By.xpath(".//*[@id=':1g4']/b"));
email.click();

回答1:


think that u r in page after login. Now use the below code:

List<WebElement> email = driver.findElements(By.cssSelector("div.xT>div.y6>span>b"));

for(WebElement emailsub : email){
    if(emailsub.getText().equals("Your Subject Here") == true){

           emailsub.click();
           break;
        }
    }

this will just click on ur mail if it matches the subject string.




回答2:


Do log in in gmail

// open ff and go to gmail login page 

        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin?sacu=1&scc=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&osid=1&service=mail&ss=1&ltmpl=default&rm=false#identifier");

        // log in in to the gmail

        driver.findElement(By.xpath("//*[@id='Email']")).sendKeys("ur id");
        driver.findElement(By.xpath("//*[@id='next']")).click();
        driver.findElement(By.xpath("//*[@id='Passwd']")).sendKeys("ur password");
        driver.findElement(By.xpath("//*[@id='signIn']")).click();

now click on the email (first) or of ur choice

List<WebElement> a = driver.findElements(By.xpath("//*[@class='yW']/span"));
System.out.println(a.size());
            for(int i=0;i<a.size();i++){
                System.out.println(a.get(i).getText());
                if(a.get(i).getText().equals("Gmail Team")){  // if u want to click on the specific mail then here u can pass it
                    a.get(i).click();
                }
            }



回答3:


Don't login to Gmail with selenium which is sceurity illegal asper google . Use Java mail.ogin to Gmail with smtp server deatails. Which is fast . This API provides a lot methods to get deiffirenttype of emails




回答4:


Working solution for your problem. It uses JAVAX MAIL API and JAVA

  public GmailUtils(String username, String password, String server, EmailFolder 
    emailFolder) throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imap");
    props.setProperty("mail.imaps.partialfetch", "false");
    props.put("mail.imap.ssl.enable", "true");
    props.put("mail.mime.base64.ignoreerrors", "true");

    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imap");
    store.connect("imap.gmail.com", 993, "<your email>", "<your password>");

    Folder folder = store.getFolder(emailFolder.getText());
    folder.open(Folder.READ_WRITE);

    System.out.println("Total Messages:" + folder.getMessageCount());
    System.out.println("Unread Messages:" + folder.getUnreadMessageCount());

    messages = folder.getMessages();

    for (Message mail : messages) {
        if (!mail.isSet(Flags.Flag.SEEN)) {

            System.out.println("***************************************************");
            System.out.println("MESSAGE : \n");

            System.out.println("Subject: " + mail.getSubject());
            System.out.println("From: " + mail.getFrom()[0]);
            System.out.println("To: " + mail.getAllRecipients()[0]);
            System.out.println("Date: " + mail.getReceivedDate());
            System.out.println("Size: " + mail.getSize());
            System.out.println("Flags: " + mail.getFlags());
            System.out.println("ContentType: " + mail.getContentType());                
            System.out.println("Body: \n" + getEmailBody(mail));
            System.out.println("Has Attachments: " + hasAttachments(mail));

        }
    }
}


public boolean hasAttachments(Message email) throws Exception {

    // suppose 'message' is an object of type Message
    String contentType = email.getContentType();
    System.out.println(contentType);

    if (contentType.toLowerCase().contains("multipart/mixed")) {
        // this message must contain attachment
        Multipart multiPart = (Multipart) email.getContent();

        for (int i = 0; i < multiPart.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                System.out.println("Attached filename is:" + part.getFileName());

                MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
                String fileName = mimeBodyPart.getFileName();

                String destFilePath = System.getProperty("user.dir") + "\\Resources\\";

                File fileToSave = new File(fileName);
                mimeBodyPart.saveFile(destFilePath + fileToSave);

                // download the pdf file in the resource folder to be read by PDFUTIL api.

                PDFUtil pdfUtil = new PDFUtil();
                String pdfContent = pdfUtil.getText(destFilePath + fileToSave);

                System.out.println("******---------------********");
                System.out.println("\n");
                System.out.println("Started reading the pdfContent of the attachment:==");


                System.out.println(pdfContent);

                System.out.println("\n");
                System.out.println("******---------------********");

                Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
                Files.delete(fileToDeletePath);
            }
        }

        return true;
    }

    return false;
}

public String getEmailBody(Message email) throws IOException, MessagingException {

    String line, emailContentEncoded;
    StringBuffer bufferEmailContentEncoded = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
    while ((line = reader.readLine()) != null) {
        bufferEmailContentEncoded.append(line);
    }

    System.out.println("**************************************************");

    System.out.println(bufferEmailContentEncoded);

    System.out.println("**************************************************");

    emailContentEncoded = bufferEmailContentEncoded.toString();

    if (email.getContentType().toLowerCase().contains("multipart/related")) {

        emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
        emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);

        System.out.println(emailContentEncoded);

        String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
        return emailContentDecoded;
    }

    return emailContentEncoded;

}



回答5:


if you want to select a part of email title, try this

List<WebElement> gmails = driver.findElements(By.cssSelector("div.xT>div.y6>span>b"));
for(WebElement gmail : gmails){
   if(gmail.getText().indexOf("Your title email") != -1){
                gmail.click();
                break;
   }
}


来源:https://stackoverflow.com/questions/36198527/how-to-click-on-a-particular-email-from-gmail-inbox-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!