如何在Gmail中打开每封电子邮件?

时间:2017-04-03 18:57:22

标签: java selenium webdriver gmail

请帮忙关注一下?

  1. 我需要打开收件箱中的每封电子邮件。
  2. 从中获取内容。
  3. public void main() {
        driver.get("https://mail.google.com");
    
        // gmail login
        driver.findElement(By.id("Email")).sendKeys("email");   
        driver.findElement(By.id("next")).click();
        driver.findElement(By.id("Passwd")).sendKeys("password");
        driver.findElement(By.id("signIn")).click();
    
    
        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 = "Команда Gmail";
    
        // real logic starts here
        for(int i=0;i<unreademeil.size();i++){
            if(unreademeil.get(i).isDisplayed()==true){
    
                if(unreademeil.get(i).getText().equals(MyMailer)){
                    System.out.println("Yes we have got mail form " + MyMailer);
    
                    break;
                }else{
                    System.out.println("No mail form " + MyMailer);
                }
            }
        }
        //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("Я")) //to click on a specific mail.
            {
                a.get(i).click();
                System.out.println(driver.findElement(By.xpath("//*[@id=\":9v\"]/div[1]")).getText());
                driver.navigate().back();
            }
        }
    

    我也尝试过JavaMail API。

    但似乎我在他们的代码中做错了。

        public static void bot() throws Exception {
            Properties props = System.getProperties();
            props.setProperty("mail.store.protocol", "imaps");
    
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "@gmail.com",
                    "password");
    
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
    
            System.out.println("Total Message:" + folder.getMessageCount());
            System.out.println("Unread Message:"
                    + folder.getUnreadMessageCount());
    
            Message[] messages = null;
            boolean isMailFound = false;
            Message mailFromGod= null;
    
            //Search for mail from God
            for (int i = 0; i < 5; i++) {
                messages = folder.search(new SubjectTerm("t");
                        folder.getMessages());
                //Wait for 10 seconds
                if (messages.length == 0) {
                    Thread.sleep(10000);
                }
            }
    
            for (Message mail : messages) {
                if (!mail.isSet(Flags.Flag.SEEN)) {
                    mailFromGod = mail;
                    System.out.println("Message Count is: "
                            + mailFromGod.getMessageNumber());
                    isMailFound = true;
                }
            }
                String line;
                StringBuffer buffer = new StringBuffer();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(mailFromGod
                                .getInputStream()));
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                System.out.println(buffer);
    
                String registrationURL = buffer.toString().split("http://www./?")[0]
                        .split("href=")[1];
                System.out.println(registrationURL);
            }
        }
    } 
    

    并试试这个

    package Bots;
    
    import javax.mail.*;
    import java.util.Properties;
    
    public class checkemail {
    
        public static void check(String host, String storeType, String user,
                                 String password)
        {
            try {
    
                //create properties field
                Properties properties = new Properties();
    
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", "995");
                properties.put("mail.pop3.starttls.enable", "true");
                Session emailSession = Session.getDefaultInstance(properties);
    
                //create the POP3 store object and connect with the pop server
                Store store = emailSession.getStore("pop3s");
    
                store.connect(host, user, password);
    
                //create the folder object and open it
                Folder emailFolder = store.getFolder("INBOX");
                emailFolder.open(Folder.READ_ONLY);
    
                // retrieve the messages from the folder in an array and print it
                Message[] messages = emailFolder.getMessages();
                System.out.println("messages.length---" + messages.length);
    
                for (int i = 0, n = messages.length; i < n; i++) {
                    Message message = messages[i];
                    System.out.println("---------------------------------");
                    System.out.println("Email Number " + (i + 1));
                    System.out.println("Subject: " + message.getSubject());
                    System.out.println("From: " + message.getFrom()[0]);
                    System.out.println("Text: " + message.getContent().toString());
                    //System.out.println("Message" + message.getDescription().toString());
    
                }
    
                //close the store and folder objects
                emailFolder.close(false);
                store.close();
    
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
    
            String host = "pop.gmail.com";// change accordingly
            String mailStoreType = "pop3";
            String username = "test@gmail.com";// change accordingly
            String password = "test";// change accoredingly
    
            check(host, mailStoreType, username, password);
    
        }
    
    }
    

    结果: ... 电子邮件号码7 主题:测试 来自:谷歌

    文字:javax.mail.internet.MimeMultipart@612fc6eb

    电子邮件号码8 主题:测试 来自:谷歌 文字:javax.mail.internet.MimeMultipart@1060b431

    但是如何从消息中获取普通文本

2 个答案:

答案 0 :(得分:0)

message.getContent().toString()

以上代码适用于多部分消息的纯文本,请在下面的代码中包含循环。

Multipart multipart = (Multipart) message.getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
System.out.println("Body: "+bodyPart.getContent());
content= bodyPart.getContent().toString();
System.out.println(content);
}

如果您的问题由此解决,请让我们更新。

答案 1 :(得分:0)

我修改了一下代码。一切似乎都按预期工作。

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class email {

private WebDriver driver;

@BeforeMethod
public void beforeMethod() {

    String exePath = "chromedriver_win32\\chromedriver.exe";
    System.setProperty("webdriver.chrome.driver", exePath);
    driver = new ChromeDriver();

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://google.com/");

}

@AfterMethod
public void afterMethod() {
    driver.quit();
}

@Test
public void main() throws InterruptedException {

    String email = "email";
    String password = "password";

    driver.get("https://mail.google.com");
    driver.findElement(By.id("Email")).sendKeys(email);
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys(password);
    driver.findElement(By.id("signIn")).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 = "FROMTESTEMAIL";
    String bodyemail = "";
    int i = 0;

        for (i = 0; i < unreademeil.size(); i++) {
            if (unreademeil.get(i).isDisplayed() == true) {

                unreademeil.get(i).click();
                System.out.println(bodyemail);

                driver.findElement(By.xpath("//a[contains(text(),'Click here')]")).click();

                Thread.sleep(5000);
                System.out.println("Your current page is: " + driver.getTitle());

                ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
                driver.switchTo().window(tabs2.get(0));
                driver.close();
                driver.switchTo().window(tabs2.get(1));

                System.out.println("Your current page is: " + driver.getTitle());
                driver.findElement(By.xpath("/html/body/div/div[5]/div[2]/div[1]/a")).click();
                System.out.println("It is started");
                Thread.sleep(3000);

              // do something after clicking on the required link
              // ...  

                try {
                    Alert confirmationAlert = driver.switchTo().alert();
                    String alertText = confirmationAlert.getText();
                    System.out.println("Alert text is " + alertText);
                    confirmationAlert.accept();
                } catch (Exception e) {
                    System.out.println("The alerts haven't been found");
                    e.printStackTrace();
                }

                driver.get("https://mail.google.com");
                Thread.sleep(5000);
                i--;
                unreademeil = driver.findElements(By.xpath("//*[@class='zF']"));
            }
         }
      }
   }