I'd like to fetch mail from a mailbox regularly using a Node daemon. The call to the connection method is made in app.js.
The javascript file I use to connect to my mailbox (mail.js):
var imap = new Imap({
user: '[email protected]',
password: config.get.gmail_password,
host: 'xxxxx',
port: 993,
tls: true
});
var fetchMail = function()
{
console.log('Connection');
imap.connect();
};
//fetchMail();
imap.once('ready', function() {
console.log('Ready');
imap.search([ 'UNSEEN', ['FROM', 'xxxx'] ], function(err, results)
{
// Do Stuff
}
exports.fetchMail = fetchMail;
If I use fetchMail() directly from mail.js, everything is fine.
However, when I try to call it from app.js:
var mail = require('./js/mail');
mail.fetchMail()
Then, the method stay in the fetchMail() function from mail.js and the imap.once('ready', function())is never triggered.
I guess it is a scope issue with the imap var in mail.js.
How can I fix this?
EDIT
I solved this in a way I don't like. I wrote everything's related to the imap var inside the fecthMail()function.
Please, do not hesitate to write a more efficient answer to this.
module.exports = fetchMail;inmail.js?fetchMail is not a functioninapp.js.app.js, you need to first export frommail.jsthen use itapp.jsby doingrequire