Search code examples
javascriptgoogle-apps-scriptbase64gmailgmail-api

can't decode gmail message returned by users.messages.get()


I am using Google Apps Script API users.messages.get() to read gmail message. I have a valid message id. Below is my code snippet:

let message = Gmail.Users.Messages.get("me", id);
let encodedBody = message["payload"]["parts"][0]["body"]["data"];
let body = Utilities.base64Decode(encodedBody);

Per the doc at this link, encodedBody should be a base64 encoded string, and when I use Try this method at this page, it indeed return a base64 encoded string that can be decoded on this website. However, when I run the google apps script, it throws this exception: Exception: Could not decode string.. Upon checking, the encodedBody looks like this when I print it in the goole apps script console:

[60,33,68,79,67,84,89,80,69,32,104,116,109...]

It's a huge array of integers instead of a base64 encoded string. May I ask why this happens? Can anyone provide a working example in google apps script to read the gmail message body? I can't use GmailApp.search().getMessages() for reasons mentioned in this question.


Solution

  • From your showing value of [60,33,68,79,67,84,89,80,69,32,104,116,109...] and if the value of encodedBody is [60,33,68,79,67,84,89,80,69,32,104,116,109...], I thought that the value is the byte array of int8Array for Google Apps Script. In this case, how about the following modification?

    From:

    let body = Utilities.base64Decode(encodedBody);
    

    To:

    let body = Utilities.newBlob(encodedBody).getDataAsString();
    
    • By this modification, the text data is retrieved from the byte array.

    • If the data is binary data, how about the following modification?

        let body = DriveApp.createFile(Utilities.newBlob(encodedBody));
      
      • By this, the data is created as a file to the root folder.

    Note:

    • If an error occurs, please check the value of encodedBody again.

    Reference: