Как открыть каждое письмо в gmail?

Не могли бы вы помочь с подпиской?

  1. Мне нужно открывать каждое электронное письмо, которое у меня есть в папке "Входящие".
  2. Получите содержание от этого.

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

    }

}

Результат: ... Email Number 7 Тема: test От: Google

Текст: javax.mail.internet.MimeMultipart@612fc6eb

Электронная почта № 8 Тема: тестирование От: Google Текст: javax.mail.internet.MimeMultipart@1060b431

но как получить нормальный текст из сообщения

2 ответа

Решение
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);
}

Обновим, если ваша проблема решится этим.

Я немного изменил код. Кажется, все работает как ожидалось.

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']"));
            }
         }
      }
   }
Другие вопросы по тегам