Gmail API - Parse message content (Base64 decoding?) with Javascript

artis3n picture artis3n · Jul 14, 2014 · Viewed 17.5k times · Source

I'm trying to use the Gmail API to get a user's email, grab the message subject and body, and then display it on a webpage. I'll be doing other stuff with it, but this is the part that I am having difficulty with. I am using Angular.js.

Here is my API call:

function makeApiCall() {
  gapi.client.load('gmail', 'v1', function() {
    var request = gapi.client.gmail.users.messages.list({
      labelIds: ['INBOX']
    });
    request.execute(function(resp) {
      var content = document.getElementById("message-list");
      angular.forEach(resp, function(message) {
        var email = gapi.client.gmail.users.messages.get({'id': message.id});
        // var raw = email.payload.parts;
        // console.log(raw);
        content.innerHTML += JSON.stringify(email) + "<br>";
      })
    });
  });
}

So gapi.client.gmail.users.messages.list returns an array of my messages, with their ID numbers. That is working.

The call to gapi.client.gmail.users.messages.get({<specific message ID>}) outputs this - {"B":{"method":"gmail.users.messages.get","rpcParams":{},"transport":{"name":"googleapis"}}}.

Not sure what that is, but trying to get the message payload (email.payload.parts), results in undefined. So, how can I get the message content?

Also, I would assume that if I can get the message contents, I would then have to Base64 decode the contents to get some English out of it. Any suggestions for that would be of great help also. I've found this: https://github.com/kvz/phpjs, but since I'm not sure how to go about getting the message contents so that I can try and decode them, so not sure if that php.js is of an help in that regard.

Answer

FullStack picture FullStack · Feb 20, 2015

Regarding the Base64 decoding, you can use

atob(dataToDecode)

For Gmail, you'll also want to replace some characters:

atob( dataToDecode.replace(/-/g, '+').replace(/_/g, '/') ); 

The above function is available to you in JavaScript (see ref). I use it myself to decode the Gmail messages. No need to install extra stuff. As an interesting tangent, if you want to encode your message to Base64, use btoa.

Now, for accessing your message payload, you can write a function:

var extractField = function(json, fieldName) {
  return json.payload.headers.filter(function(header) {
    return header.name === fieldName;
  })[0].value;
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");

referenced from my previous SO Question and

var part = message.parts.filter(function(part) {
  return part.mimeType == 'text/html';
});
var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));