Reputation: 2286
I am having a problem creating an google script that would run every night. The code runs fine when I run it from the script file and behaves as expected, however when performed by an installed trigger I get the following:
TypeError: Cannot read property "length" from undefined. (line 17, file "Main")
EDIT: To be clear I know that the particular query used has to return results as running the same script from the script editor works fine
Code:
function doGet(query) {
var sSheet = sheetSelect(), //calls spreadsheet selection function and assigns the spreadsheet to variable
queriedMessages, //object to store the queried messages list
pageToken, //string token value that will be pulled from the queredMessages
auth = 'me';
if (!query) query = 'in:all newer_than:1d -is:chats -in:trash';
do {
queriedMessages = Gmail.Users.Messages.list(auth, {'q':query, 'pageToken':pageToken}); //callls the Gmail API to query messages
dataOutput(sSheet, queriedMessages.messages, queriedMessages.messages.length); //calls function to output all data to spreadsheet from the current list
pageToken = queriedMessages.nextPageToken; //gets the next page token from the list
}
while (pageToken); //the loop is executed until there are no more next page tokens left
}
Any ideas why it behaves so differently? I have tried providing userId for a specific e-mail. Seems like this might be some kind of authentication issue but I cannot figure out how to fix it other than forgetting about Gmail API and go a roundabout way of using Gmail App as it seems to be an issue with Gmail API method messages.list()
Thank You for any help in advance!
I managed to fix the issue. The problem was me wanting to leave an option to pass on a query with the function call. The problem then is that the installed trigger actually passed on a variable to the query variable and a new one is then not set.
Upvotes: 2
Views: 710
Reputation: 112827
I think it's much simpler than that. If I list messages in the last day, I get:
Request:
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=newer_than%3A1d
Response:
{
"messages": [
{
"id": "150612f9d7f83db9",
"threadId": "150611d4e92b7a5f"
}, ...
]
}
If I list messages in the last second, I get:
Request:
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=newer_than%3A1s
Response:
{
"resultSizeEstimate": 0
}
In other words, queriedMessages.messages
will be undefined
if you get no messages with that particular query, and queriedMessages.messages.length
will give rise to your error.
Upvotes: 1