2

Since MS is dropping basic-auth support on IMAP this fall (2020) I tried setting up OAuth2.

I've successfully setup an application and I'm able to retrieve an access token using the msal4j lib. I use the ROPC flow.

My token seems to be OK and has the needed scope https://graph.microsoft.com/IMAP.AccessAsUser.All.

Nevertheless, the login attempt on the IMAP server still fails with no further error message (AUTHENTICATE failed).

public class IMAPMailReceiverTest {

    public static final void main(String[] strg) throws Exception {
        PublicClientApplication app = PublicClientApplication.builder("[app-id]")
                .authority("https://login.microsoftonline.com/[tenant-id]/").build();

        Set<String> scope = new HashSet<>();
        scope.add("https://graph.microsoft.com/IMAP.AccessAsUser.All");

        CompletableFuture<IAuthenticationResult> future = app.acquireToken(UserNamePasswordParameters
                .builder(scope, "test@domain.com", "[password]".toCharArray()).build());

        future.handle((res, ex) -> {
            if (ex != null) {
                System.out.println("message - " + ex.getMessage());
                return "Unknown!";
            }
            System.out.println("Access Token - " + res.accessToken());
            System.out.println("ID Token - " + res.idToken());

            try {
                Properties props = new Properties();
                props.put("mail.imap.ssl.enable", "true");
                props.put("mail.imaps.auth.mechanisms", "XOAUTH2");
                props.put("mail.imaps.auth.plain.disable", true);
                Session session = Session.getInstance(props);
                Store store = session.getStore("imaps");
                store.connect("Outlook.office365.com", "test@domain.com", res.accessToken());
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            return res;
        });

        future.join();
        TimeUnit.SECONDS.sleep(300);
    }

}

Has anyone successfully fetched emails using IMAP/OAuth2 workflow for Office365 accounts?

(I'm using the latest versions of msal4j lib and Java Mail.)

  • Can you use fiddler to capture the detailed error message? – Tony Ju Apr 10 '20 at 08:22
  • I played around with this today because the company I work for uses different methods of access one uses IMAP/SMTP the other uses EWS access. Funny thing is, that with EWS.AccessAsUser.All as scope, I can also login with IMAP. But the scope you mentioned alone is not enough to login. – jumper85 May 14 '20 at 13:51

0 Answers0