Kunok Kunok - 2 months ago 22
Node.js Question

CRON Node.js Gmail API script

How do I properly setup Gmail API script that sends emails?

I am about to use this method and I started building my script from this quickstart guide.

Is there alternative way to do this without using OAuth 2 validation? Or a way to validate once for all?

Answer

I found solution using JWT to authorize OAuth2. You need to have admin account to create Domain wide delegation service account. Then in Developer console you need to download service key JSON file which you load as credentials.

First fetch all users like this: (here you need to use account with admin directory rights)

const google = require('googleapis');
const gmail = google.gmail('v1');
const directory = google.admin('directory_v1');
const scopes = [
  'https://www.googleapis.com/auth/gmail.readonly',
  'https://www.googleapis.com/auth/admin.directory.user.readonly'
];
const key = require('./service_key.json');

var authClient = new google.auth.JWT(
  key.client_email,
  key,
  key.private_key,
  scopes,
  "authorized@mail.com"
);

authClient.authorize(function(err, tokens){
  if (err) {
    console.log(err);
    return;
  }

  directory.users.list(
    {
      auth: authClient,
      customer: 'my_customer',
      maxResults: 250,
      orderBy: 'email'
    }, (err, resp) => {
    if (err) {
      console.log(err);
      return;
    }

    console.log(resp);
  });

});

Then you need to fetch Thread lists (100 per request (page)). And for each thread object you need to call get method for full thread. When using Gmail API authorize as user you want to fetch emails from. In request as userId use value 'me'.

Comments