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

前端 未结 4 769
野的像风
野的像风 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:43

    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, '/'));
    

提交回复
热议问题