0

I am trying to use Nodemailer in express server with Oauth from Office 365 but I am getting Can't create new access token for user and {"code": "EAUTH", "command": "AUTH XOAUTH2" error. It seems like nodemailer is unable to obtain either the access token and refresh token and the user is not being authenticated to send mails.

  const transporter = nodemailer.createTransport({
    host: "smtp.office365.com",
    port: 587,
    secure: false,
    tls: {
      ciphers: "SSLv3"
    },
    requireTLS: true,
    auth: {
      type: "OAuth2",
      user: process.env.SENDER_EMAIL,
      clientId: "CLIENT_ID",
      clientSecret: "CLEINT_SECRET",
      accessUrl: "https://login.microsoftonline.com/SOMETHING_SECRET_HERE/oauth2/v2.0/authorize"
      // pass: process.env.SENDER_PASSWORD
    }
  });

enter image description here

I am not familiar with OAuth 2.0 with Office 365 to begin with so there could be some configurations error etc. The nodemailer works fine if I use my account credentials though. Can someone please suggest me something to try out or let me know if my config is wrong.

calvert
  • 631
  • 10
  • 33

1 Answers1

0

Please note that, accessUrl is an endpoint for requesting new access token.

As you have passed Authorization endpoint, please try changing it to OAuth 2.0 token endpoint (v2).

You can find this endpoint value in the Portal like below:

Go to Azure Portal -> Azure Active Directory -> App Registrations -> Your App

enter image description here

Alternatively, you can make use of Microsoft Graph API to send the mails like below:

Make sure to have Mail.Send permission consented before using the below query:

POST https://graph.microsoft.com/v1.0/me/sendMail

{
"message": {
"subject": "Regarding leave approval",
"body": {
"contentType": "Text",
"content": "Please approve my leave request."
},

"toRecipients": [
{
"emailAddress": {
"address": "XXXXX"
}
}
],

"ccRecipients": [
{
"emailAddress": {
"address": "XXXXX"
}
}
]
},
"saveToSentItems": "false"
}

Response:

enter image description here

The mail was successfully triggered like below:

enter image description here

For more in detail, please refer the below links:

Send mail - Microsoft Graph v1.0 | Microsoft Docs

Modern Oauth2 authentication for sending mails using Nodemailer nodejs by Sivaprakash-MSFT

Sridevi
  • 10,599
  • 1
  • 4
  • 17