2
votes

I am creating an app to add watch for the app user's gmail account using Google Apps Script.

For testing the working of watch, I have used the following app script code which I got from a youtube tutorial by Spencer Easton (https://www.youtube.com/watch?v=wjHp9_NAEJo)

function doPost(e)
{
    var message = JSON.parse(e.postData.getDataAsString()).message;
    var data = Utilities.newBlob(Utilities.base64Decode(message.data)).getDataAsString();
    var ss = SpreadsheetApp.openById('my_google_sheet_id').getSheets()[0];
    ss.appendRow([new Date(), message.message_id, data, "newMail"]);

    return 200;
}


function enrollEmail() {

    var watchRes = Gmail.newWatchRequest();

    watchRes.labelIds = ["INBOX"];
    watchRes.labelFilterAction = "include";
    watchRes.topicName = "projects/project-id-12345/topics/gmailTrigger";

    var response = Gmail.Users.watch(watchRes, "me");
}


function doGet()
{
    enrollEmail();
}

Then I published the app using the following steps:

1.  Deploy as web app
2.  Execute the app as: Me
3.  Who has access to the app: Anyone, even anonymous

Now the watch is working fine for my gmail account.

But my requirement is to watch all the users authenticated in my app.

So, I tried publishing the app using the following steps:

1.  Deploy as web app
2.  Execute the app as: User accessing the web app
3.  Who has access to the app: Anyone

Now the app asks for authentication to the users who visits the web app URL. But the watch does not work for the user's gmail account and for my gmail account.

Again I published the app using the first method (Execute the app as: Me), now the watch works for the authenticated user's account and my account.

How to configure the Google Apps Script so that I can add watch for the user's who authenticates my app.

2
"But the watch does not work for the user's gmail account and for my gmail account." Could you expand on this please? What exactly doesn't work?Serge Hendrickx
The doPost() was not called when a new email gets added to the inbox. (user's account & my account)Arun D

2 Answers

0
votes

Since you already watch a topic, the next thing to do is to setup how to receive the notifications (setting up webhooks).

The good thing about your case is that Spencer Easton's github has an entry for Gmail API with Push Notification.

0
votes

I had the same problem.

Have you tried

return HtmlService.createHtmlOutput("");

instead of

return 200;

in the doPlot function?

Maybe at the time Spencer Easton wrote his code, return 200; was still allowed by Apps Script but now doPlot should strictly return an HtmlOutput object