从 Selenium 连接到 OUTLOOK 365 Java

Connecting to OUTLOOK365 from Selenium Java

我有一个应用程序可以在输入凭据后向我的电子邮件发送验证码。我需要从收件箱中读取验证码。我正在使用 Outlook,我的组织使用 OUTLOOK365 的 MAPI 协议。

谁能帮我解决这个问题?

这是打印所有收件箱的完整代码message.You需要提取正文并找到验证码

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

    }
}

此外,您还需要以下依赖

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

使用 Graph API 可以访问 Outlook。

  1. 您需要在 Azure App.Usauly 中注册,由 IT Team.you 完成,将获得客户端 ID、客户端密码和 Tennant ID。

  2. 那么你需要使用Client credential autorization provider来获取tokken。以下是来自 Microsoft Java SDK 的代码,共享于 https://github.com/Azure-Samples/ms-identity-java-daemon/blob/master/msal-client-credential-secret/src/main/java/ClientCredentialGrant.java

    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("https://graph.microsoft.com/v1.0/users/<yourEmailID>//mailFolders/Inbox/messages?$search=\"<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");
        }
    }