If you're struggling with Microsoft SMTP via OAuth 2 . . .
. . . you are not alone.
Help is available.
This took me a while to figure out, and I assume there may be others struggling too. I made my way through all the Entra stuff to set up a client credentials workflow to send email through a Microsoft 365 account. I was able to successfully retrieve my token, but I couldn't ever get it to authenticate with the SMTP server using the %Net.SMTP class. There were two parts to fixing this.
First, the authenticator's access token needs to be more than JUST the access token. It has to be formatted as:
set smtp.authenticator.AccessToken = "user="_email_address_$C(1)_"auth=Bearer "_token_$C(1,1)where email_address is the email address you're sending from and token is the OAuth token you got from the server.
Second, the default %Net.SASL.XOAUTH2 mechanism does not behave the way the SMTP server expects it to. Specifically, it sends no initial response to the server then it starts authenticating, but the server expects to see that access token immediately. To accommodate that, you'll have to create a class that extends %Net.SASL.XOAUTH2 and overrides just one simple method:
Class User.MSOAUTH2 Extends %Net.SASL.XOAUTH2
{
/// Start authentication based on UserName and AccessToken using the XOAUTH2 SASL mechanism.
Method Start(ByRef response As %String) As %Boolean
{
if (..AccessToken="") quit 0
set response=..AccessToken ;in the original class, no response is sent here
set ..state=1
quit 1
}
}
Then to use that class instead of the default one, you'll have to point the authenticator's mechanism list at it as follows:
set smtp.authenticator.MechanismList = "XOAUTH2:MSOAUTH2"After making these adjustments, I was able to send SMTP email as expected through smtp.office365.com on port 587 with an SSL configuration set up. I am not familiar enough with how the Email Outbound Adapter works within productions to give any advice on how to implement these changes there.
Comments
THANK YOU - I am sure this will benefit many people!