How to fix 'A1 NO AUTHENTICATE failed.' error in Node.js script

ShivaKarthik Rao 20 Reputation points
2023-09-15T14:14:01.2766667+00:00

Below is my code I don't know what I am doing wrong. Please Help!

(async () => {
  try {
    const Imap = require('node-imap');
    const { create } = require('simple-oauth2');
    // Configure your OAuth2 credentials
    const credentials = {
      client: {
        id: 'xxxxxxx',
        secret: 'xxxxxxxx',
      },
      auth: {
        tokenHost: 'https://login.microsoftonline.com',
        tokenPath: '/common/oauth2/v2.0/token'
      },
    };
    // Create an OAuth2 client
    const oauth2Client = create(credentials);
    // Generate an OAuth2 access token
    async function getAccessToken() {
      const tokenParams = {
        refresh_token: 'xxxxx',
      };
      const result = await oauth2Client.accessToken.create(tokenParams).refresh();
      const authData = [
        'user=' + ('xxxxxxxxx' || ''),
        'auth=Bearer ' + result.token.access_token,
        '',
        ''
      ];
      return Buffer.from(authData.join('\x01'), 'utf-8').toString('base64');
    };
    // Connect to the IMAP server
    async function connectImap() {
      const mailId = 'xxxxxxxxx';
      const accessToken = await getAccessToken();
      let base64Encoded = Buffer.from([`user=${mailId}`, , `auth=Bearer ${accessToken}`, '', ''].join('\x01'), 'utf-8').toString('base64');
      const imap = new Imap({
        user: 'xxxxxxxxx',
        xoauth2: base64Encoded,
        host: 'outlook.office365.com',
        port: 993,
        tls: true,
        tlsOptions: { rejectUnauthorized: true },
        debug: console.log
      });
      imap.connect();

      imap.once('ready', function () {
        console.log("Server status: %s", imap.state);
        imap.getBoxes((error, mailboxes) => {
          if (error) throw error;
          console.log('Mailboxes:');
          Object.keys(mailboxes).forEach((mailbox) => {
            console.log(mailbox);
          });
          imap.end();
        });
        imap.openBox('INBOX', true, function (err, box) {
          if (err) throw err;
          let f = imap.seq.fetch('1:1', {
            bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
            struct: true
          });
          f.on('message', function (msg, seqno) {
            console.log('Message #%d', seqno);
          });
        });
      });
      imap.on('error', (err) => {
        console.log("err", err);
      });
    }
    // Call the connectImap function
    await connectImap();
  } catch (error) {
    console.log('Error while fetching details', error);
  }
})();
Outlook
Outlook
A family of Microsoft email and calendar products.
4,503 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,320 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. ShivaKarthik Rao 20 Reputation points
    2023-09-15T14:16:52.4766667+00:00

    Screenshot 2023-09-15 at 7.39.25 PM


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.