title: Gmail API sending email error 401:Invalid Credentials
body: <p>I'm developing with express a web page that when the client clicks in "Send E-mail" redirect to google asking for permission to send email through the client email and after the client gave the permission redirect back and send the email.</p>
  
  <p>The code so far:</p>
  
  <pre><code>'use strict';
  
  const express = require('express');
  const googleAuth = require('google-auth-library');
  const request = require('request');
  
  let router = express.Router();
  let app = express();
  
  const SCOPES = [
      'https://mail.google.com/'
      ,'https://www.googleapis.com/auth/gmail.modify'
      ,'https://www.googleapis.com/auth/gmail.compose'
      ,'https://www.googleapis.com/auth/gmail.send'
  ];
  const clientSecret = '***********';
  const clientId = '**************'; 
  const redirectUrl = 'http://localhost:8080/access-granted';
  const auth = new googleAuth();
  const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  const authUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: SCOPES
  });
  
  function sendEmail(auth, content, to , from, subject) {
      let encodedMail = new Buffer(
          `Content-Type: text/plain; charset="UTF-8"\n` +
          `MIME-Version: 1.0\n` +
          `Content-Transfer-Encoding: 7bit\n` +
          `to: ${to}\n` +
          `from: ${from}\n` +
          `subject: ${subject}\n\n` +
  
          content
      )
      .toString(`base64`)
      .replace(/\+/g, '-')
      .replace(/\//g, '_');
  
      request({
          method: "POST",
          uri: `https://www.googleapis.com/gmail/v1/users/me/messages/send`,
          headers: {
              "Authorization": `Bearer ${auth}`,
              "Content-Type": "application/json"
          },
          body: JSON.stringify({
              "raw": encodedMail
          })
      },
      function(err, response, body) {
          if(err){
              console.log(err); // Failure
          } else {
              console.log(body); // Success!
          }
      });
  
  }
  
  app.use('/static', express.static('./www'));
  app.use(router)
  
  router.get('/access-granted', (req, res) =&gt; {
      sendEmail(req.query.code, 'teste email', 'teste@gmail.com', 'teste@gmail.com', 'teste');
      res.sendfile('/www/html/index.html', {root: __dirname})
  })
  
  router.get('/request-access', (req, res) =&gt; {
      res.redirect(authUrl);
  });
  
  router.get('/', (req, res) =&gt; {
      res.sendFile('/www/html/index.html', { root: __dirname });
  });
  
  const port = process.env.PORT || 8080;
  app.listen(port, () =&gt; {
      console.log(`Server running at http://localhost:${port}`);
  });
  
  module.exports = app;
  </code></pre>
  
  <p>Every time I try to send a simple E-mail I receive the error 401: Invalid Credentials. But I'm passing in Authorization the client code auth that google sends just gave me...</p>