Google Drive API sending PDF attachments in emails

Viewed 118

I have some node.js code that reads in a PDF file using Google Drive API drive.files.get()... (it's a file that is sourced on our Google team/shared drives). I convert the returned stream to a single base64 data chunk with something like this:

    // read using drive.files.get() into 'pdfStream'
    //...
    let pdf64 = '';

    pdfSream.on('readable', function () { 
      var chunk = pdfStream.read();

      if (chunk != null) {
        var chunk64 = chunk.toString('base64');
        pdf64 += chunk64;
      }
    });
    pdfStream.on('end', function () {
      // Do SendGrid email with pdf64 as attachment
    });

Note that the final goal is to send an email with the PDF. I haven't included much of the code because this all works great - as long as the email recipient is on our company's domain. For external email recipients, the PDF attachment is unviewable and cannot be downloaded - at least this is what the situation appears to be.

I didn't think that access-restrictions and permissions would stay with data that is read directly using drive.files.get(). Is this a thing? I would suspect SendGrid except that we send attachments in other areas of our code with no issue.

Thoughts anyone? Much appreciated! ~Bob

1 Answers

I was able to fix it. The permissions thing was a red herring - the pdf attachments were corrupt and our company email system was just more lenient with the errors than others (like Gmail). I refactored the above code to first create a complete array of data, then converted that array to base64:

    // read using drive.files.get() into 'pdfStream'
    //...
    let pdfChunks = [];

    // Read through stream chunks and concat them together
    pdfStream.on('readable', function () {
      var chunk = pdfStream.read();

      if (chunk != null) {
        pdfChunks.push(chunk);
      }
    });
    // On the end of the stream, convert to base64 and email the Pdf
    pdfStream.once('end', function () {
      let pdfBin = Buffer.concat(pdfChunks);
      let pdf64 = pdfBin.toString('base64');
      //...
      // Do SendGrid email with pdf64 as attachment
    });

Cheers! ~Bob

Related