'Getting error while reading outlook mails in Node.js
Goal: I am trying to read the mails (outlook) with certain filters like 'from specified user','read','sent' etc. Used a module "IMAP" for parsing. I have to read the mail and download and store attachments from the mail in a certain location (preferably local). But my code is failing to connect to the mail server.
Below is my code which results in 'Auth:timeout error' when I ran.
Please let me know what is wrong with my code. Thanks in advance!
var Imap = require('imap'),
inspect = require('util').inspect;
var fs = require('fs'), fileStream;
var buffer = '';
var myMap;
var imap = new Imap({
user: "put user id here",
password: "put your password here",
host: "outlook.office365.com", //this may differ if you are using some other mail services like yahoo
port: 993,
tls: true,
// connTimeout: 10000, // Default by node-imap
// authTimeout: 5000, // Default by node-imap,
debug: console.log, // Or your custom function with only one incoming argument. Default: null
tlsOptions: true,
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments
});
function openInbox(cb) {
imap.openBox('INBOX', false, cb);
}
imap.once('ready', function () {
openInbox(function (err, box) {
if (err) throw err;
imap.search(['UNSEEN', ['SUBJECT', 'Give Subject Here']], function (err, results) {
if (err) throw err;
var f = imap.fetch(results, { bodies: '1', markSeen: true });
f.on('message', function (msg, seqno) {
console.log('Message #%d' + seqno);
console.log('Message type' + msg.text)
var prefix = '(#' + seqno + ') ';
msg.on('body', function (stream, info) {
stream.on('data', function (chunk) {
buffer += chunk.toString('utf8');
console.log("BUFFER" + buffer)
})
stream.once('end', function () {
if (info.which === '1') {
console.log("BUFFER" + buffer)
}
});
console.log(prefix + 'Body');
stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
});
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();
Solution 1:[1]
It's not exactly what you asked for but an alternative implementation that uses ImapFlow module instead of node-imap, and that I just verified to work against Outlook looks like the script below. If you still get timeouts etc. then it is probably a firewall issue.
const { ImapFlow } = require("imapflow");
const fs = require("fs").promises;
const client = new ImapFlow({
host: "outlook.office365.com",
port: 993,
secure: true,
auth: {
user: "[email protected]",
pass: "secretpass",
},
logger: false, // set to true if you want to see IMAP transaction logs
});
// can't run await in main scope, have to wrap it to an async function
async function main() {
// establish the connection and log in
await client.connect();
// open INBOX folder
let mailbox = await client.mailboxOpen("INBOX");
// list messages matching provided criteria
for await (let msg of client.fetch(
{
// search query to filter messages
// https://imapflow.com/global.html#SearchObject
seen: false,
subject: "Give Subject Here",
},
{
// attributes to request for
// https://imapflow.com/global.html#FetchQueryObject
uid: true,
flags: true,
internalDate: true,
bodyStructure: true,
// include full message body in the response as well
source: true,
}
)) {
// extract variables
let { seq, uid, flags, bodyStructure, internalDate, source } = msg;
console.log(`#${seq} Attributes:`, { seq, uid, flags, bodyStructure, internalDate });
// store message body as an eml file
await fs.writeFile(`msg-${seq}.eml`, source);
}
// close the connection
await client.logout();
}
main().catch(console.error);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andris |
