bbottema/simple-java-mail

Enhancement: Add support for OAUTH2 authentication

chris-cynation opened this issue · 5 comments

Hi,

I was wondering what OAuth2 support there is and if there are plans to support it if not.

OAuth2... how? This is an SMTP library, it connects and authenticates with SMTP servers. I'm not sure where OAth2 comes into the picture here.

I guess this might be important as it is now required when connecting /authenticating to smtp.office365.com if not changes for a mailbox (which is not always possible, especially if a customer does not want to pass on the actuall password to external solutions in the future). At least the server response states 250-AUTH LOGIN XOAUTH2 and plain login using username and password does not work anymore. Also gmail does accept OAuth2 authentication.

So the question would be how to achieve this type of authentication with simple-java-mail assuming that there is a working OAuth2 token at hand.

Interesting! Apparently, this was already possible in Sun JavaMail.

First of all, to start testing this in order to develop this feature, there are a few steps to get stuff working (took a while to figure this out):

  1. Create a new Google API Project with new consent screen and OAuth client credentials, as described at github.com/nfo/gmail_xoauth.
  2. Now generate a new OAuth2 token using this new Google API and to do that you need an app that will invoke the consent screen in the browser for the actual login. Unfortunately the oauth2.py Python script from that repo is old and broken, but luckily you can find new working instructions here, which uses a newer Python script from getmail6.
  3. Then with this OAth2 token string, go to yet another project, gmail_xoauth, and open the Java oauth2 module, configure Sun JavaMail dependencies and all and run OAuth2Authenticator.java with the IMAP commented out in the static void main. With a valid OAuth2 token this should run and finish without errors.

I just discovered JavaMail / Jakarta Mail already supported it out of the box, without using Google's version.

Guess I'll have to start over :|

OAUTH2 authentication is now supported with the release of 7.6.0!

It's super simple, just use TransportStrategy.OAUTH2 (which is based on TransportStrategy.SMTP_TLS) and use your OAuth2 token as password.

MailerBuilder
  .withSMTPServer("server host", 587, "username", yourOAuth2Token)
  .withTransportStrategy(TransportStrategy.SMTP_OAUTH2)
  .buildMailer()
  .sendMail(email);

Of course, the real challenge now is how are you going to get that OAuth2 token? That varies from platform to platform.