1
votes

I'm trying to read emails responded by the Gmail API.

I have trouble accessing all the "parts". And don't have great ways to traverse through the response. I'm also lost as to how many parts can exist so that I can make sure I read the different email responses properly. I've shortened the response below...

{ "payload": { "mimeType": "multipart/mixed", "filename": "", ], "body": { "size": 0 }, "parts": [ {

"body": {
 "size": 0
},
"parts": [
 {
  "partId": "0.0",
  "mimeType": "text/plain",
  "filename": "",
  "headers": [
   {
    "name": "Content-Type",
    "value": "text/plain; charset=\"us-ascii\""
   },
   {
    "name": "Content-Transfer-Encoding",
    "value": "quoted-printable"
   }
  ],
  "body": {
   "size": 2317,
   "data": "RGVhciBNSVQgQ2x1YiBWb2x1bnRlZXJzIGluIEFzaWEsDQoNCkJ5IG5vdyBlYWNoIG9mIHlvdSBzaG91bGQgaGF2ZSByZWNlaXZlZCBpbnZpdGF0aW9ucyB0byB0aGUgcmVjZXB0aW9ucyBpbiBib3RoIFNpbmdhcG9yZSBhbmQgSG9uZyBLb25nIHdpdGggUHJlc2lkZW50IFJlaWYgb24gTm92ZW1iZXIgNyBhbmQgTm92ZW1iZXIg"
  }
 },
 {
  "partId": "0.1",
  "mimeType": "text/html",
  "filename": "",
  "headers": [
   {
    "name": "Content-Type",
    "value": "text/html; charset=\"us-ascii\""
   },
   {
    "name": "Content-Transfer-Encoding",
    "value": "quoted-printable"
   }
  ],
  "body": {
   "size": 9116,
   "data": "PGh0bWwgeG1sbnM6dj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp2bWwiIHhtbG5zOm89InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206b2ZmaWNlOm9mZmljZSIgeG1sbnM6dz0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTpvZmZpY2U6d29yZCIgeG1sbnM6bT0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9vZmZpY2UvMjA"
  }
 }
]    },    {
"partId": "1",
"mimeType": "text/plain",
"filename": "",
"body": {
 "size": 411,
 "data": "X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX18NClRoYW5rIHlvdSBmb3IgYWxsb3dpbmcgdXMgdG8gcmVhY2ggeW91IGJ5IGVtYWlsLCB0aGUgbW9zdCBpbW1lZGlhdGUgbWVhbnMgZm9yIHNoYXJpbmcgaW5mb3JtYXRpb24gd2l0aCBNSVQgYWx1bW5pLiANCklmIHlvdSB3b3VsZCBsaWtlIHRvIHVuc3Vic2NyaWJlIGZyb20gdGhpcyBtYWlsaW5nIGxpc3Qgc2VuZCBhIGJsYW5rIGVtYWlsIHRvIGxpc3RfdW5zdWJzY3JpYmVAYWx1bS5taXQuZWR1IGFuZCBwdXQgdGhlIGxpc3QgbmFtZSBpbiB0aGUgc3ViamVjdCBsaW5lLg0KRm9yIGV4YW1wbGU6DQpUbzogbGlzdF91bnN1YnNjcmliZUBhbHVtLm1pdC5lZHUNCkNjOg0KU3ViamVjdDogYXNpYW9mZg0K"
}    }   ]  } }

Is there something I'm missing?

4

4 Answers

2
votes

A MIME message is not just an array it's a full blown tree structure. So you'll have to traverse it to correctly handle it. Luckily JSON parsers are plentiful and the problem can easily be handled with recursion. In many languages there exist very useful email parsing libraries that can make accessing traditional parts (e.g. the text/plain or text/html displayable part, or attachments) not too laborious.

0
votes

The MIME parts you are looking for are in an array. JSON does not tell you up front how many items are in an array. Even MIME itself does not provide a way of knowing how many parts are present without looking at the entire message. You will just have to traverse the entire array to know how many parts are in it, and process each part as you encounter it.

0
votes

To know how much parts exists, you can just use the Length property.

Example :

json.payload.parts.length

For your example, this property is 2 because there are 2 parts.

0
votes

You'll have to set up walker functions to traverse through the json and pick out the bits you are after. Here is a part of what I wrote. This may help you jumpstart your code. NOTE: this is used inside of wordpress...hence the special jQuery call. Not needed if you do not need to use jquery inside wordpress.

function makeApiCall() {
gapi.client.load('gmail', 'v1', function() {
    //console.log('inside call: '+myquery);
  var request = gapi.client.gmail.users.messages.list({
    'userId': 'me',
    'q': myquery
  });
  request.execute(function(resp) {
    jQuery(document).ready(function($) {
          //console.log(resp);
          //$('.ASAP-emailhouse').height(300); 
          $.each(resp.messages, function(index, value){
                messageId = value.id;
                var messagerequest = gapi.client.gmail.users.messages.get({
                    'userId': 'me',
                    'id': messageId
                  });//end var message request
                messagerequest.execute(function(messageresp) {
                    //console.log(messageresp); 
                    $.each(messageresp, responsewalker);
                    function responsewalker(key, response){
                        messagedeets={};
                        $.each(messageresp.payload.headers, headerwalker);
                        function headerwalker(headerkey, header){
                            if(header.name =='Date'){
                                d = new Date(header.value);
                                var curr_date = d.getDate();
                                var curr_month = d.getMonth() + 1; //Months are zero based
                                var curr_year = d.getFullYear();
                                var formatteddate = curr_month+'/'+curr_date+'/'+curr_year;
                                messagedeets['date']=formatteddate;
                                //$('.ASAP-emailhouse').append('<p>'+header.value+'</p>');
                            }
                            if(header.name =='Subject'){
                                //console.log(header.value);
                                messagedeets.subject=header.value;
                            }
                        }
                        messagedeets.body = {};
                        $.each(messageresp.payload.parts, walker);
                        function walker(partskey, value) {
                            //console.log(value.body);
                            if (value.body.data !== "undefined") {
                                //console.log(value.body);
                                var messagebody = atob(value.body.data);
                                messagedeets.body.partskey = messagebody;
                            }
                        console.log(messagedeets);
                        $('.ASAP-emailhouse').append('<div class="messagedeets"><p class="message-date">'+messagedeets.date+': <span class="message-subject">'+messagedeets.subject+'</span></p><p>'+messagedeets.body.partskey+'</p></div>');
                        }//end responsewalker
                        //$('.ASAP-emailhouse').append('</li>');
                    }
                    //$('.ASAP-emailhouse').append('</ul>');
                });//end message request
            });//end each message id
      });//end jquery wrapper for wordpress
  });//end request execute list messages
});//end gapi client load gmail

}