Javax mail Office Exchange with oAuth2 (Token) SMTP

Viewed 1579

Can someone give me aguide to authenticate to office 365 exchange with javax mail with oAuth2?

transport.connect(mailConfig.getMailUsername(), mailConfig.getMailPassword());

(I Tried also with Bearer + ...

Properties props = new Properties();

            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.host", "smtp.office365.com");
            props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.debug.auth", "true");
            props.put("mail.debug", "true");
            Session session = Session.getInstance(props);
            session.setDebug(true);
            Transport transport = session.getTransport("smtp");
            transport.connect(mailConfig.getMailUsername(), mailConfig.getMailPassword());

Photo of Permission for Microsoft Azure

Photo of Permission for Microsoft Azure

Here is my stackstrace:

DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 [...]
535 5.7.3 Authentication unsuccessful [ZR0P278CA0118.CHEP278.PROD.OUTLOOK.COM]
2 Answers

Using the client credentials flow for SMTP Authentication is currently not supported.

See the NOTE in Microsoft's doc on the SMTP Protocol Exchange.

Also, see this post from the Exchange Team Blog. They just added support for IMAP and POP in June 2022. SMTP is not yet there and they have not shared a timeline for when they expect to have it. They report that they will continue to support basic authentication (username/password) for SMTP.

I think you need to use

props.put("mail.smtp.sasl.mechanisms.oauth2.oauthToken", accessToken);

and then use null as a password

transport.connect("smtp.office365.com", mailConfig.getMailUsername(), null);

For me this was working

DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AS9PR04CA0130.outlook.office365.com Microsoft ESMTP MAIL Service ready at Wed, 29 Jun 2022 10:36:34 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
Related