Home > Software engineering >  Google Apps Script - cannot save mail message to PropertiesService
Google Apps Script - cannot save mail message to PropertiesService

Time:08-05

I have a Google Script attached to a spreadsheet and I try to save an email message to Properties Service. However I receive an error when calling a method on the object I read back from PropertiesService. Code to reproduce the problem:

function TEST21() {
  // get a message fromn inbox
  let threads = GmailApp.search("");
  let originalMsg = threads[0].getMessages()[0];
  console.log(originalMsg.getSubject()); // works fine and logs the email subject
  
  //save message
  PropertiesService.getScriptProperties().setProperty("key", JSON.stringify(originalMsg));
  // retrieve message back
  let retrievedMsg = PropertiesService.getScriptProperties().getProperty("key");
  retrievedMsg = JSON.parse(retrievedMsg);
  console.log(retrievedMsg.getSubject()); // throws ERROR: TypeError: retrievedMsg.getSubject is not a function
}

CodePudding user response:

When I saw your script, at PropertiesService.getScriptProperties().setProperty("key", JSON.stringify(originalMsg));, it seems that Class GmailMessage is stored to PropertiesService. In this case, this value is not JSON data. I think that this is the reason for your issue. In your situation, how about using the message ID? When your script is modified, it becomes as follows.

Modified script:

function TEST21() {
  let threads = GmailApp.search("");
  let originalMsg = threads[0].getMessages()[0];
  console.log(originalMsg.getSubject());

  PropertiesService.getScriptProperties().setProperty("key", originalMsg.getId());
  let retrievedMsg = PropertiesService.getScriptProperties().getProperty("key");
  retrievedMsg = GmailApp.getMessageById(retrievedMsg);
  console.log(retrievedMsg.getSubject());
}
  • By using the message ID, you can retrieve the value using console.log(retrievedMsg.getSubject()); at the last line.

References:

  • Related