java - 如何在 Selenium WebDriver 中检查邮件验证?

标签 java selenium selenium-webdriver testng gmail-imap

我需要验证 Gmail 中是否已收到电子邮件。所以我尝试了以下代码。但我没有得到结果。你能帮我解决一下这个问题吗?

以下代码是:

public static void getPassword(String email, String password) 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", email, 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 mailFromProx = null;

        // Search for mail from Prox with Subject = 'Email varification Testcase'
        for (int i = 0; i <= 5; i++) {

            messages = folder.search(new SubjectTerm("Email varification Testcase"), folder.getMessages());
            // Wait for 20 seconds
            if (messages.length == 0) {
                Thread.sleep(20000);
            }
        }

        // Search for unread mail
        // This is to avoid using the mail for which
        // Registration is already done
        for (Message mail : messages) {
            if (!mail.isSet(Flags.Flag.SEEN)) {
                mailFromProx = mail;
                System.out.println("Message Count is: " + mailFromProx.getMessageNumber());
                isMailFound = true;
            }
        }

        // Test fails if no unread mail was found
        if (!isMailFound) {
            throw new Exception("Could not find new mail from iGotThis :-(");

            // Read the content of mail and get password
        } else {
            String line;
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(mailFromProx.getInputStream()));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            System.out.println(buffer);
            String result = buffer.toString().substring(buffer.toString().indexOf("is:") + 1,
                    buffer.toString().indexOf("3. Start enjoying an easier life!"));
            String resultxx = result.substring(4, result.length() - 1);

            //Print passsword
            System.out.println(resultxx);

            Properties prop = new Properties();
            OutputStream output = null;

            try {

                output = new FileOutputStream(Constant.Path_UserPassFile);
                // set the properties value in property file
                prop.setProperty("User_Password", resultxx);
                PropsUtils.setProperties().setProperty("User_Password", resultxx);
                // save properties to project root folder
                prop.store(output, null);

            } catch (IOException io) {
                io.printStackTrace();
            }
            System.out.println("Password = " + prop.getProperty("User_Password"));
        }
    }
}

我尝试搜索很多结果,但没有什么不清楚的。您能给我提供完美的结果吗?

如果您有任何关于 Selenium 邮件测试的结果,请在此处提供,让我在这里尝试。

最佳答案

这是您问题的有效解决方案。它使用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;

}

关于java - 如何在 Selenium WebDriver 中检查邮件验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52493149/

相关文章:

java - 在 Linux 终端中打开一个小程序

java - 如何获取 Java 类结构的哈希值?

python - 使用 Python 通过 Selenium WebDriver 打开 chrome 扩展

java - 如何使用 Selenium Webdriver Java 查找表行号

java - 是否有任何 BSD 许可的 Oracle JVM(Windows)替代方案?

java - 将证书添加到 java keystore ,仍然出错

javascript - 如何使用 Selenium IDE 识别滚动条位置

python - 使用 Python 和 Selenium 为什么我无法通过链接文本找到链接?

java - Selenium 从 WebDriver 获取 HTML(或 JSON)响应

c# - 错误 : There is already an option for the mobileEmulation capability. 请改用它。参数名称:capabilityName