Connecting to Outlook365 from Selenium Java

I have an application that sends a verification code to my Email after entering credentials. I need to read the verification code from my inbox. I am using Outlook and my organization uses the MAPI protocol for OUTLOOK365.

Can anyone help me with this?

2 Answers

Here is the full code which will print all the inbox message.You need to extract the body and find the verification code

 package solution;
import java.util.Properties;


import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class test {
    public static String username =null;
    public static String password1 =null;
    public static void check(String host, String storeType, String user,
                             String password)
    { username= user;
        password1 = password;
        try {



            //create properties field
            Properties properties = new Properties();


            properties.put("mail.imap.host", host);
            properties.put("mail.imap.port", "993");
            //    properties.put("mail.imap.starttls.enable", "true");
            //   properties.setProperty("mail.imap.socketFactory.fallback", "false");
            // properties.setProperty("mail.imao.socketFactory.port",
            //       String.valueOf("993"));
            //properties.put("mail.imap.auth", "false");
            // properties.put("mail.debug.auth", "true");
            properties.put("mail.imaps.ssl.trust", "*"); // This is the most IMP property

            Session emailSession = Session.getDefaultInstance(properties);





            //create the POP3 store object and connect with the pop server

            Store store = emailSession.getStore("imaps"); //try imap or impas
            store.connect(host, user, password);
            //  store.connect(host, 993, 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 < 10; 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());

            }

            //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 = "outlook.office365.com";
        String mailStoreType = "imaps";
        String username = "USERNAME";
        String password = "PASSWORD";

        check(host, mailStoreType, username, password);

    }
}

Also, you need the following dependency

 <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
2

Using the Graph API one can access the Outlook.

  1. you need to register in Azure App.Usauly done by IT Team.you would get a client Id, Client secret and Tennant id.

  2. then you need to use Client credential autorization provider to get the tokken. below is the code from Microsoft Java SDK shared at

    import com.microsoft.aad.msal4j.ClientCredentialFactory;
    import com.microsoft.aad.msal4j.ClientCredentialParameters;
    import com.microsoft.aad.msal4j.ConfidentialClientApplication;
    import com.microsoft.aad.msal4j.IAuthenticationResult;
    import com.nimbusds.oauth2.sdk.http.HTTPResponse;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Collections;
    import java.util.Properties;
    import java.util.concurrent.CompletableFuture;
    
    class ClientCredentialGrant {
    
        private static String authority;
        private static String clientId;
        private static String secret;
        private static String scope;
        private static ConfidentialClientApplication app;
    
        public static void main(String args[]) throws Exception{
    
            setUpSampleData();
    
            try {
                BuildConfidentialClientObject();
                IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
                String usersListFromGraph = getUsersListFromGraph(result.accessToken());
    
                System.out.println("Users in the Tenant = " + usersListFromGraph);
                System.out.println("Press any key to exit ...");
                System.in.read();
    
            } catch(Exception ex){
                System.out.println("Oops! We have an exception of type - " + ex.getClass());
                System.out.println("Exception message - " + ex.getMessage());
                throw ex;
            }
        }
        private static void BuildConfidentialClientObject() throws Exception {
            
            // Load properties file and set properties used throughout the sample
            app = ConfidentialClientApplication.builder(
                    clientId,
                    ClientCredentialFactory.createFromSecret(secret))
                    .authority(authority)
                    .build();               
        }
    
        private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
            
            // With client credentials flows the scope is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal), and then granted by a tenant administrator
            ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                    Collections.singleton(scope))
                    .build();
            
            CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
            return future.get();
        }
    
        private static String getMessagesGraph(String accessToken) throws IOException {
            URL url = new URL(""<yourSubject>\"");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + accessToken);
            conn.setRequestProperty("Accept","application/json");
    
            int httpResponseCode = conn.getResponseCode();
            if(httpResponseCode == HTTPResponse.SC_OK) {
    
                StringBuilder response;
                try(BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))){
    
                    String inputLine;
                    response = new StringBuilder();
                    while (( inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                }
                return response.toString();
            } else {
                return String.format("Connection returned HTTP code: %s with message: %s",
                        httpResponseCode, conn.getResponseMessage());
            }
        }
    
        /**
         * Helper function unique to this sample setting. In a real application these wouldn't be so hardcoded, for example
         * different users may need different authority endpoints or scopes
         */
        private static void setUpSampleData() throws IOException {
            // Load properties file and set properties used throughout the sample
            Properties properties = new Properties();
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
            authority = properties.getProperty("AUTHORITY");
            clientId = properties.getProperty("CLIENT_ID");
            secret = properties.getProperty("SECRET");
            scope = properties.getProperty("SCOPE");
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest