Search code examples
node.jsgmailimapimapflow

How to connect to Gmail using node.js imapflow?


I'm using imapflow package like this:

import config from './config.js';
import { ImapFlow } from 'imapflow';

const client = new ImapFlow({
    host: 'imap.gmail.com',
    port: 993,
    secure: true,
    auth: {
        user: '[email protected]',
        pass: '123'
    }
});

await client.connect();

console.log('OK');

And it throws with Invalid credentials (Failure). I've quadruple-checked that login and password are correct, IMAP is enabled in GMail settings. Less than secure apps aren't enabled though, and I'd prefer to keep it that way. When I try to use the same credentials in Thunderbird, it opens an OAuth login window, which I suppose I should somehow incorporate with imapflow? Or is there a different solution?


Solution

  • Gmail does not allow accessing its IMAP services by using plain username and password. You should first get OAuth2.0 credentials via the Gmail api example (here) and then should convert it to xoauth2.

    let {installed: {client_id, client_secret}} = require('./client_secret') // the client_secret.json file
    let xoauth2gen = xoauth2.createXOAuth2Generator({
      user: '*******', // the email address
      clientId: client_id,
      clientSecret: client_secret,
      refreshToken: refresh_token
     })
    
    xoauth2gen.getToken(function(err, xoauth2token) {
      if (err) {
        return console.log(err)
      }
            
      let imap = new Imap({
         xoauth2: xoauth2token,
         host: 'imap.gmail.com',
         port: 993,
         tls: true,
         authTimeout: 10000,
         debug: console.log,
     })