如何在Selenium中点击gmail收件箱中的特定电子邮件?

时间:2016-03-24 10:56:42

标签: java selenium selenium-webdriver automated-tests

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

我正在尝试下面的代码-Plz建议我继续采取行动。

gmail登录后 -

  

第1个Ihv点击收件箱链接--->>然后促销--->>然后我点击特定的电子邮件

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

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

5 个答案:

答案 0 :(得分:4)

认为你登录后的页面。现在使用以下代码:

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

如果匹配主题字符串,则只需点击你的邮件。

答案 1 :(得分:1)

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

现在点击电子邮件(第一个)或您的选择

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

答案 2 :(得分:1)

适用于您的问题的解决方案。它使用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;

}

答案 3 :(得分:0)

如果您想选择电子邮件标题的一部分,请尝试使用

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

答案 4 :(得分:0)

请勿使用selenium登录Gmail,而selenium是非法的谷歌。使用带有smtp服务器deatails的Java mail.ogin到Gmail。这很快。此API提供了很多方法来获取电子邮件的deiffirenttype