java 如何从 Selenium 的 gmail 收件箱中单击特定电子邮件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36198527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:03:34  来源:igfitidea点击:

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

javaseleniumselenium-webdriverautomated-tests

提问by Bharat Mane

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

我想点击一个特定的电子邮件,在这种情况下我该怎么办?我看到有一个带有多个索引的 Webtable,我可以选择 1 并单击它。有没有人有代码如何处理 WebDriver 中的 webTables?在下面的屏幕中查看确切情况 - http://screencast.com/t/XRbXQVygNkN6

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

我正在尝试使用以下代码 - 请建议我进行其余操作。

After gmail Login-

gmail登录后-

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();

回答by noor

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.

如果它与主题字符串匹配,这将只单击您的邮件。

回答by eduliant

Do log in in gmail

登录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();
                }
            }

回答by bhargav

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

不要使用 selenium 登录 Gmail,这在 google 中是非法的。使用 Java mail.ogin 到带有 smtp 服务器详细信息的 Gmail。这是快速的。这个 API 提供了很多方法来获取不同类型的电子邮件

回答by Atul Sharma

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

您的问题的工作解决方案。它使用 JAVAX MAIL API 和 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;

}

回答by Lam Vu

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;
   }
}