简体   繁体   中英

Open mails from Gmail inbox using selenium webdriver using java

I need to open mails from Gmail inbox using selenium webdriver using java in Eclipse IDE. Is there a way to do this using xpath?

The ideal way would be to not use selenium to automate gmail but rather use the Gmail API (https://developers.google.com/gmail/api/#how_do_i_find_out_more ) to verify the message was successfully sent. If you do not want to learn how to check the messages at the API level I would highly recommend using the HTML version of gmail using this link as the initial url for gmail ( https://mail.google.com/mail/?ui=html ) using gmail with javascript enabled will make it much harder to have a reliable test script.

Here is my solution without any thread.sleap() and etc.

   driver.get("https://mail.google.com/");                                                                                                                        

   WebElement userElement = wait.until(ExpectedConditions.elementToBeClickable(By.id("identifierId")));                                                           
   userElement.click();                                                                                                                                           
   userElement.clear();                                                                                                                                           
   userElement.sendKeys(properties.getProperty("username"));                                                                                                      

   WebElement identifierNext = wait.until(ExpectedConditions.elementToBeClickable(By.id("identifierNext")));                                                      
   identifierNext.click();                                                                                                                                        

   WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.name("password")));                                                         
   passwordElement.click();                                                                                                                                       
   passwordElement.clear();                                                                                                                                       
   passwordElement.sendKeys(properties.getProperty("password"));                                                                                                  

   WebElement passwordNext = wait.until(ExpectedConditions.elementToBeClickable(By.id("passwordNext")));                                                          
   passwordNext.click();                                                                                                                                          

   WebElement composeElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@role='button' and (.)='Compose']")));                            
   composeElement.click();                                                                                                                                        

   WebElement maximizeEmailElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//td//img[2]")));                                               
   maximizeEmailElement.click();                                                                                                                                  

   WebElement sendToElement = wait.until(ExpectedConditions.elementToBeClickable(By.name("to")));                                                                 
   sendToElement.click();                                                                                                                                         
   sendToElement.clear();                                                                                                                                         
   sendToElement.sendKeys(String.format("%s@gmail.com", properties.getProperty("username")));                                                                     

   WebElement subjectElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@name = 'subjectbox']")));                                        
   subjectElement.click();                                                                                                                                        
   subjectElement.clear();                                                                                                                                        
   subjectElement.sendKeys(properties.getProperty("email.subject"));                                                                                              

   WebElement emailBodyElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@role = 'textbox']")));                                         
   emailBodyElement.click();                                                                                                                                      
   emailBodyElement.clear();                                                                                                                                      
   emailBodyElement.sendKeys(properties.getProperty("email.body"));                                                                                               

   WebElement sendMailElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[text()='Send']")));                                            
   sendMailElement.click();                                                                                                                                       

   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'Message sent')]")));                                                   
   List<WebElement> inboxEmails = wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//*[@class='zA zE']"))));                   

   for(WebElement email : inboxEmails){                                                                                                                           
       if(email.isDisplayed() && email.getText().contains("email.subject")){                                                                                                                                   
           email.click();                                                                                                                                         

           WebElement label = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@title,'with label Inbox')]")));                    
           WebElement subject = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[contains(text(),'Subject of this message')]")));          
           WebElement body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Single line body of this message')]")));   

       }                                                                                                                                                          
   }       

I agree to @sonhu and done the same. Sorted this problem using JAVAX MAIL API (not GMAIL API).

    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;

}

Hi plz try like this below code checks unread mail only

public static void main(String[] args) {
    // TODO Auto-generated method stub. 

System.setProperty("webdriver.chrome.driver","D:\\eclipseProject\\StackOverFlow\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();

driver.get("https://accounts.google.com/ServiceLogin?");

// gmail login
driver.findElement(By.id("Email")).sendKeys("your gmail username");
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys("your gmail password");
driver.findElement(By.id("signIn")).click();

// some optional actions for reaching gmail inbox
driver.findElement(By.xpath("//*[@title='Google apps']")).click();
driver.findElement(By.id("gb23")).click();

// now talking un-read email form inbox into a list
List<WebElement> unreademeil = driver.findElements(By.xpath("//*[@class='zF']"));

// Mailer name for which i want to check do i have an email in my inbox 
String MyMailer = "Stack over flow";

// real logic starts here
for(int i=0;i<unreademeil.size();i++){
    if(unreademeil.get(i).isDisplayed()==true){
        // now verify if you have got mail form a specific mailer (Note Un-read mails)
        // for read mails xpath loactor will change but logic will remain same
        if(unreademeil.get(i).getText().equals(MyMailer)){
            System.out.println("Yes we have got mail form " + MyMailer);
            // also you can perform more actions here 
            // like if you want to open email form the mailer
            break;
        }else{
            System.out.println("No mail form " + MyMailer);
        }
    }
}

}

package package1; import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.chrome.ChromeDriver;

public class class1 {
    public static void main(String[] args) throws InterruptedException{
        System.setProperty("webdriver.chrome.driver","C:\\Users\\name\\Desktop\\chromedriver.exe");
        ChromeDriver driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
        driver.findElement(By.id("identifierId")).sendKeys("****@gmail.com");
        driver.findElement(By.id("identifierNext")).click();
        driver.findElement(By.xpath("//input[@aria-label='Enter your password' and @name='password']")).sendKeys("********");
        Thread.sleep(200);
        driver.findElement(By.id("passwordNext")).click();


    }}

/// From XL Sheet Gmail userid & password will pic Login to G-mail & UnRead Mails only filter (Based on Unique in that mail) - in that mail any Hyser link or web link it will open (Based on X Path) ////////////////////////////////////////////////////////

public static void NM_RA_Mail_Click_RALDCaseIDLink() throws Exception {
    String G_userid = null;
    String G_password = null;

xlfilepath = "C:\Users\Desktop\BIPS\Code\GLDT-TestCases-for-Automation007.xlsx";

    try { 

        FileInputStream fStream = new FileInputStream(new String(xlfilepath));//Enter the path to your excel here

        // Create workbook instance referencing the file created above
        XSSFWorkbook workbook = new XSSFWorkbook(fStream);

        // Get your first or desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0); // getting first sheet Based on index([0,1,...]     

        //XSSFSheet sheet = workbook.getSheet("Master_Test_Data"); //Based on sheet name
        XSSFRow row1 = sheet.getRow(5);
        XSSFCell cell1 = row1.getCell(2);

        XSSFRow row2 = sheet.getRow(6);
        XSSFCell cell2 = row2.getCell(2);

        G_userid = cell1.toString();
        G_password = cell2.toString();
        
        
        
        
        
        XSSFRow row3 = sheet.getRow(9);
        XSSFCell cell3 = row3.getCell(2);

        XSSFRow row4 = sheet.getRow(10);
        XSSFCell cell4 = row4.getCell(2);

        NM_RA_userid = cell3.toString();
        NM_RA_password = cell4.toString();

        fStream.close();
        workbook.close(); 

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    String projectPath = System.getProperty("user.dir");
    

// System.setProperty("webdriver.chrome.driver",projectPath+"\drivers\chromedriver\chromedriver.exe"); // driver = new ChromeDriver();

  System.setProperty("webdriver.edge.driver", projectPath+"\\drivers\\edgedriver\\msedgedriver.exe");
    WebDriver driver = new EdgeDriver();

    driver.manage().window().maximize();
    String url = "https://mail.google.com/";

    driver.get(url);
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
    WebElement email_phone = driver.findElement(By.xpath("//input[@id='identifierId']"));
    email_phone.sendKeys(G_userid);
    driver.findElement(By.id("identifierNext")).click();

    WebElement password = driver.findElement(By.xpath("//input[@name='password']"));
    
    WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(20));
    wait.until(ExpectedConditions.elementToBeClickable(password));
    password.sendKeys(G_password);
    driver.findElement(By.id("passwordNext")).click(); 

    //--------------------------//
    
    
    
    Thread.sleep(5000);
    List<WebElement> a = driver.findElements(By.className("zE")); //un-Mailes it will read ...
    System.out.println(a.size());
    
                for(int i=0;i<a.size();i++)
                {
                    //Thread.sleep(5000);
                    System.out.println(a.get(i).getText());
                    Thread.sleep(3000);

                   // if(a.get(i).getText().contains("4211"))
                        //if(a.get(i).getText().contains("(GLDT-4211)"))
                    if(a.get(i).getText().contains(GLDT_Case_ID))
                    ///GLDT_Case_ID - Mail containes subject or something yu want o search unique thing in that mail
                                
                    {  // if u want to click on the specific mail then here u can pass it
                                Thread.sleep(5000);
                                    a.get(i).click();
                                    
                                    WebElement BIPS_Link = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html[1]/body[1]/div[7]/div[3]/div[1]/div[2]/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[3]/div[1]/table[1]/tr[1]/td[1]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[3]/div[3]/div[1]/div[1]/div[2]/span[1]/span[1]/a[1]")));
                                    BIPS_Link.click();   /// inside mail it will open the link
                                    
                                    break;   
                                }
                }
                
                
//open a mail from the gmail inbox.
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("Support")) //to click on a specific mail.
                    {                                           
                    a.get(i).click();
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM