Reading Mails with IMAP with OAuthentication in Node JS

KRANTHI KUMAR REDDY 1 Reputation point
2022-12-23T18:14:19.56+00:00

Hi Team,
I am using IMAP for Reading Mails With Micosoft O Authentication. I am getting below Error. I added below permissions also but getting error. please help me on this issue.

273779-image.png
<= 'A1 NO AUTHENTICATE failed.'
Error: AUTHENTICATE failed.
at Connection._resTagged (Project\node_modules\imap\lib\Connection.js:1502:11)
at Parser.<anonymous> (Project\node_modules\imap\lib\Connection.js:194:10)
at Parser.emit (node:events:513:28)
at Parser._resTagged (Project\node_modules\imap\lib\Parser.js:175:10)
at Parser._parse (Project\node_modules\imap\lib\Parser.js:139:16)
at Parser._tryread (Project\node_modules\imap\lib\Parser.js:82:15)
at Parser._cbReadable (Project\node_modules\imap\lib\Parser.js:53:12)
at TLSSocket.emit (node:events:513:28)
at emitReadable_ (node:internal/streams/readable:590:12)
at process.processTicksAndRejections (node:internal/process/task_queues:81:21) {
type: 'no',
textCode: undefined,
source: 'authentication'
}
[connection] Ended
Connection ended
[connection] Closed

Please Find My Code..

const msal = require('@azure/msal-node');
var Imap = require('node-imap'),
inspect = require('util').inspect;
var buffer = require('buffer/').Buffer;

const msalConfig = {
auth: {
clientId: configuration.OAuthenticationDetails.ClientID,
authority: configuration.OAuthenticationDetails.aadEndpoint + '/' + configuration.OAuthenticationDetails.TenantID,
clientSecret: configuration.OAuthenticationDetails.ClientScreatValue
}
}

const tokenRequest = {
scopes: ["https://outlook.office365.com/.default"],
};

const cca = new msal.ConfidentialClientApplication(msalConfig);
let tokenInfo = "";
var AccessToken;

async function getTokenInfo() {
tokenInfo = await cca.acquireTokenByClientCredential(tokenRequest);
AccessToken = tokenInfo.accessToken;

let base64Encoded =  Buffer.from([`user=${configuration.mailNotification_config_Receive.username}`, `auth=Bearer ${AccessToken}`, '', ''].join('\x01'), 'utf-8').toString('base64');  
var imap = new Imap({  
    xoauth2: base64Encoded,  
    host: 'outlook.office365.com',  
    port: 993,  
    tls: true,  
    debug: console.log,  
    authTimeout: 25000,  
    connTimeout: 30000,  
    tlsOptions: {  
        rejectUnauthorized: false,  
        servername: 'outlook.office365.com'  
    }  
});  

function openInbox(cb) {  
    imap.openBox('INBOX', true, cb);  
}  

imap.once('ready', function () {  
    openInbox(function (err, box) {  
        if (err) throw err;  
        var f = imap.seq.fetch('1:3', {  
            bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',  
            struct: true  
        });  
        f.on('message', function (msg, seqno) {  
            console.log('Message #%d', seqno);  
            var prefix = '(#' + seqno + ') ';  
            msg.on('body', function (stream, info) {  
                var buffer = '';  
                stream.on('data', function (chunk) {  
                    buffer += chunk.toString('utf8');  
                });  
                stream.once('end', function () {  
                    console.log(  
                        prefix + 'Parsed header: %s',  
                        inspect(Imap.parseHeader(buffer))  
                    );  
                });  
            });  
            msg.once('attributes', function (attrs) {  
                console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));  
            });  
            msg.once('end', function () {  
                console.log(prefix + 'Finished');  
            });  
        });  
        f.once('error', function (err) {  
            console.log('Fetch error: ' + err);  
        });  
        f.once('end', function () {  
            console.log('Done fetching all messages!');  
            imap.end();  
        });  
    });  
});  

imap.once('error', function (err) {  
    console.log(err);  
});  

imap.once('end', function () {  
    console.log('Connection ended');  
});  

imap.connect();  

}
getTokenInfo();

Microsoft Authenticator
Microsoft Authenticator
A Microsoft app for iOS and Android devices that enables authentication with two-factor verification, phone sign-in, and code generation.
5,542 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,663 questions
0 comments No comments
{count} votes