Search code examples
node.jsoauthgoogle-oauthimapgmail-imap

Node imap Xoauth2


I am using xoauth2 module to generate an xoauth2 token to connect via imap to gmail and I'm getting this error:

`

[09:50:28.806] [LOG] [connection] Connected to host
[09:50:28.873] [LOG] <= '* OK Gimap ready for requests from 31.154.25.42 q4mb701
07656lfe'
[09:50:28.881] [LOG] => 'A0 CAPABILITY'
[09:50:29.067] [LOG] <= '* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID
 XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIE
NTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH'
[09:50:29.069] [LOG] <= 'A0 OK Thats all she wrote! q4mb70107656lfe'
[09:50:29.073] [LOG] => 'A1 AUTHENTICATE XOAUTH2 ******************************************
****************************************************************************************************************************
********************************************************************************='
[09:50:29.374] [LOG] <= '+ eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2Nvc
GUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ=='
[09:50:29.377] [LOG] => '\r\n'
[09:50:29.534] [LOG] <= 'A1 NO [AUTHENTICATIONFAILED] Invalid credentials (Failu
re)'
[09:50:29.537] [ERROR] ERROR Imap:Error: Invalid credentials (Failure)
[09:50:29.755] [LOG] [connection] Ended
[09:50:29.756] [LOG] Imap: Connection ended
[09:50:29.758] [LOG] [connection] Closed`

here is my connection code:

this.setImap = function(connParams) {
    //----------------------------------------------
    console.log(connParams);
    xoauth2gen = xoauth2.createXOAuth2Generator({
      user: connParams.user,
      clientId: configAuth.googleAuth.clientID,
      clientSecret: configAuth.googleAuth.clientSecret,
      refreshToken: connParams.refresh_token,
      accessToken: connParams.access_token,
      customPayload: {
          "access_type": "offline"
      }
    });

    xoauth2gen.getToken(function(err, token) {
      if (err) {
        return console.log(err);
      }
      console.log("AUTH XOAUTH2 " + token);
      connParams.xoauth2 = token;
    });

    connParams = {
      id: 13,
      user: connParams.user,
      xoauth2: connParams.xoauth2,
      host: 'imap.gmail.com',
      port: 993,
      tls: 1,
      debug: console.log
    }
    //------------------------------------------- 
    connParams.tlsOptions = {
      rejectUnauthorized: false
    };

    console.log(connParams);
    
    self.imap = new Imap(connParams);

    this.imap.once('ready', function() {
      console.log('Imap: ready');
      self.openInbox();
    });

    this.imap.once('error', function(err) {
      console.error("ERROR Imap:" + err);
    });

    this.imap.once('end', function() {
        console.log('Imap: Connection ended');
    });
};

Checked a million time the details :(

here is the scope I'm using:

scope: ['profile', "https://mail.google.com/" ]

Solution

  • You should remove the user from the connParams and furthermore add a space in the xoauth module...