Parsing Gmail API Message to JSON

Viewed 51

I'm working on a script in GAS to get various components of emails to a spreadsheet. I want to only get the body of the most recent message, rather than the body of the message + all the past text from other messages in the thread. From what I've read, this can be done by using the Gmail API advanced service instead of GmailApp.

I'm running into issues getting messages into JSON to be able to access the body. I'm receiving an error "SyntaxError: Unexpected token , in JSON at position 2" on my JSON.parse line. I can't figure out what I'm doing incorrectly in my formatting.

arr[0] is only for testing; I will be iterating over the array once I figure out how to parse the email.


var rawMessage = Gmail.Users.Messages.get("me",arr[0],{
  "format": "raw"})

var rawMessageBytes = rawMessage.raw
console.log(typeof rawMessageBytes)
var messageBlob = Utilities.newBlob(rawMessageBytes).getDataAsString()
console.log(typeof messageBlob)
var parsedBlob = JSON.parse(rawMessageBytes)
}


1 Answers

Try this:

function getLastMessage() {
  let r = Gmail.Users.Messages.list('me');
  let a = JSON.parse(r);
  let m = GmailApp.getMessageById(a.messages[0].id);
  Logger.log(m.getDate());
  Logger.log(m.getPlainBody()); 
}
Related