I am trying to use Java Mail to connect to an IMAP server using XOAUTH2. The configuration is as follows:
Properties properties= new Properties();
properties.put("mail.imap.ssl.enable", "true");
properties.put("mail.imap.auth.mechanisms", "XOAUTH2");
properties.put("mail.imap.auth.login.disable", true);
properties.put("mail.imap.auth.plain.disable", true);
properties.put("mail.imap.auth.xoauth2.disable", false);
properties.put("mail.debug", "true");
properties.put("mail.debug.auth", "true");
Session session = Session.getInstance(properties);
store = session.getStore("imaps");
store.connect(host, username, accessToken);
As you can see, I am using all the properties to avoid any connection using another mechanism different than XOAUTH2, but the debug shows that AUTHENTICATE PLAIN
is used instead of AUTHENTICATE XOAUTH2
:
The dependency used in POM is the following:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
Finally, I can authenticate using openssl directly by using AUTHENTICATE XOAUTH2
:
What I am doing wrong? How can I make Java Mail uses the command AUTHENTICATE XOAUTH2
instead of AUTHENTICATE PLAIN
?
Thanks
After several hours of working on this, I found that the problem is with the name of the IMAP properties. I changed properties to the following, and now it works:
properties.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
Note that it is not "imap" but "imaps" with an "s" at the end.
I don't know why in many questions in Stackoverflow and the Java Mail documentation the properties appear without the "s" and apparently, it works for them.
https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html
Be aware to use a Java Mail Version equal or superior to 1.5.2. I used Java Mail 1.6.2.
Hope this can help somebody else.