Outlook
A family of Microsoft email and calendar products.
4,503 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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);
}
})();