Friday 17 March 2017

node.js Gmail API: Getting Inline/Embedded images

When grabbing an email I run the gmail.users.messages.get() and then run the following two functions to process the payload.

function getBody(message) {
  var encodedBody = '';  
  try{    
    if(typeof message.parts === 'undefined'){
      encodedBody = message.body.data;
    }    
    else{
      encodedBody = getHTMLPart(message.parts);
    }
    encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
  }
  catch(e) {} // there was a failure

  return decodeURIComponent(escape(window.atob(encodedBody)));
}
function getHTMLPart(arr) {

  for(var x = 0; x <= arr.length; x++){    
    if(typeof arr[x].parts === 'undefined'){
      if(arr[x].mimeType === 'text/html'){
        return arr[x].body.data;
      }
    }
    else{      
      return getHTMLPart(arr[x].parts);
    }
  }
  return '';
}

I then save that data into an .html file for later use. The problem is that inline images aren't embedded with base64 or any other way to retrieve that data, but are instead embedded using a unique CID.

So what I need to do is, when retrieving the payload from the above function, I need to also retrieve the embedded image and save it locally as <\CID.png> (or jpg or whatever). I can then to a replace on the message to replace the CID embed in the html with the local path of the image.

So does anyone know how or have any advice on how to get those embedded images? Thanks in advance!



via Harmonic

No comments:

Post a Comment