Kunok Kunok - 1 year ago 183
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 Source

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 = [
const key = require('./service_key.json');

var authClient = new google.auth.JWT(

authClient.authorize(function(err, tokens){
  if (err) {

      auth: authClient,
      customer: 'my_customer',
      maxResults: 250,
      orderBy: 'email'
    }, (err, resp) => {
    if (err) {



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'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download