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

前端 未结 4 761
野的像风
野的像风 2020-12-14 13:15

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

4条回答
  •  [愿得一人]
    2020-12-14 13:39

    You need to search where the body for a given mime type is, I have written a recursive function for that:

    function searchBodyRec(payload, mimeType){
        if (payload.body && payload.body.size && payload.mimeType === mimeType) {
            return payload.body.data;
        } else if (payload.parts && payload.parts.length) {
            return payload.parts.flatMap(function(part){
                return searchBodyRec(part, mimeType);
            }).filter(function(body){
                return body;
            });
        }
    }
    

    So now you can call

    var encodedBody = searchBodyRec(this.message.payload, 'text/plain');
    

    See the flatMap method up there? Classic FP method missing in js, here is how to add it (or you can use lodash.js, or underscore.js if you don't want to mess with the native objects)

    Array.prototype.flatMap = function(lambda) { 
        return Array.prototype.concat.apply([], this.map(lambda)); 
    };
    

提交回复
热议问题