Please guide how to send email using gmail api via gsuit service account

Author: meepeekCreated Oct 30, 2020Updated Mar 12, 2026
Labelstype: docssize: m

My goal is for my nodejs app to send mail to notify me if there were unhandled code exception on the server.

The code below is what I use for testing, which I modified gmail api quickstart code to use keyFile instead of oauth. However, I stuck with the error "The API returned an error: Error: Invalid Credentials".

I use this auth code with spreadsheet api before and it was success. I also did enable Domain-wide Delegation and add the app to Google Admin access control with Trusted permission level.

Now I'm stuck and cannot find any nodejs example for gmail. Please help.

import googleapis from 'googleapis'

const {google} = googleapis

const auth = new google.auth.GoogleAuth({
    keyFile: './credentials/gmail-key.json',
    scopes: ['https://www.googleapis.com/auth/gmail.send,email,profile']
})

const gmail = google.gmail({version: 'v1', auth})

// console.log(gmail.users.messages.send)

listLabels(auth)

function listLabels(auth) {
    const gmail = google.gmail({version: 'v1', auth});
    gmail.users.labels.list({
// I use service account email
      userId: 'SERVICE_ACCOUNT_NAME@APP_NAME.iam.gserviceaccount.com',
    }, (err, res) => {
      if (err) return console.log('The API returned an error: ' + err);
      const labels = res.data.labels;
      if (labels.length) {
        console.log('Labels:');
        labels.forEach((label) => {
          console.log(`- ${label.name}`);
        });
      } else {
        console.log('No labels found.');
      }
    });
  }

Source: googleapis/google-api-nodejs-client