Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving emails through Imap, by using async/await function [duplicate]

When I try to retrieve emails through imap with the code below(using an async function), I get the following console output/error:

Inbox: undefined

/Users/mainuser/node_modules/imap/lib/Connection.js:432 cb(err, self._box); ^ TypeError: cb is not a function

var Imap = require('imap');
var inspect = require('util').inspect;

var imap = new Imap({
  user: '[email protected]',
  password: 'mymailpassword',
  host: 'imap.mail.com',
  port: 993,
  tls: true
});

const openInbox = async () => {
  try {
    const inbox = await imap.openBox('INBOX', true)
    return inbox
  }catch(error){
    console.log("Error: "+ error)
  }
}

imap.once('ready', () => {
  console.log('ready')
  openInbox()
   .then(inbox => console.log('Inbox: ' + inbox))
});

imap.connect()

However, I can open the inbox and output the inbox Object using nested callbacks as shown below:

imap.once('ready', () => {
  imap.openBox('INBOX', true, (err, inbox) => {
    console.log('Inbox: ' + inbox)
  });
});

imap.connect()
like image 993
Loup G Avatar asked Oct 16 '25 13:10

Loup G


1 Answers

If you prefer to work with promises you should either write a custom wrapper around imap.openBox or wrap it with Node.js built-in util.promisify function:

const Imap = require('imap');
const promisify = require('util').promisify;

const imap = new Imap({
  user: '[email protected]',
  password: 'mymailpassword',
  host: 'imap.mail.com',
  port: 993,
  tls: true
});

const openBox = promisify(imap.openBox.bind(imap));

imap.once('ready', () => {
  console.log('ready')
  openBox('INBOX', true)
    .then(inbox => console.log(inbox))
    .catch(err => {
      console.log(err)
    })
});

imap.connect()

In order to promisify the entire API, try to wrap the imap instance in Bluebird.promisifyAll. Note the promisified methods are available with Async prefix:

const bluebird = require('bluebird');
const Imap = require('imap');

const imap = bluebird.promisifyAll(new Imap({
    user: '[email protected]',
    password: 'mymailpassword',
    host: 'imap.mail.com',
    port: 993,
    tls: true
}));

imap.once('ready', () => {
  console.log('ready')
  imap.openBoxAsync('INBOX', true)
    .then(inbox => console.log(inbox))
    .catch(err => {
      console.log(err)
    })
});

imap.connect()
like image 189
antonku Avatar answered Oct 18 '25 09:10

antonku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!