Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Selenium by (7k points)

Trying to verify whether Email is received or not in gmail. But did not get results.

The code:

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

        }

    }

}

Can you help on this?

1 Answer

0 votes
by (31.9k points)

This code uses JAVAX MAIL API and JAVA and remove the code that you don't need.

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;

}

Want to learn Selenium, checkout our Selenium training.

Related questions

0 votes
1 answer
+10 votes
5 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...