I’m having trouble with sending PDF files as email attachments using Google Drive API and nodemailer. I want to avoid downloading the file locally first, so I’m trying to stream it directly.
Here’s how I’m getting the file from Drive:
const documentData = await driveService.files.export(
{
fileId: "xyz789",
mimeType: "application/pdf",
},
{
responseType: "arrayBuffer",
}
);
Then I’m setting up the attachment for the email:
const emailAttachments = [
{
filename: "Report.pdf",
content: Buffer.from(documentData.data),
contentType: "application/pdf",
},
];
The weird thing is that the email sends fine and the PDF attachment opens, but all the pages are completely empty. If the original document has 3 pages, the attachment shows 3 blank pages. Has anyone run into this issue before? What am I doing wrong with the buffer conversion?
Try encoding: null in your drive API call instead of arraybuffer. This forces raw binary data that nodemailer handles way better. Double-check you’re not converting the buffer to string anywhere - I’ve seen middleware or logging accidentally stringify response data and break things.
Had this exact issue last month - it’s the buffer encoding that’s screwing you up. Buffer.from(documentData.data) doesn’t handle binary data from the Drive API properly. Use Buffer.from(documentData.data, 'binary') instead. Even better, switch your Drive API call to responseType: 'stream' and pipe it straight to nodemailer. The stream method saved my butt with larger PDFs and stopped the memory problems. Also double-check your Drive service account actually has permissions to export whatever file format you’re asking for.
Check if you’re working with a Google Docs file that needs proper conversion. When exporting through Drive API, some file types need specific handling for PDF conversion. I hit the same blank page issue when my source doc had formatting or embedded stuff that didn’t convert right. Grab the file metadata first to check the original mimetype, then make sure your export request actually supports what you’re trying to convert. Also test with a basic text doc to see if your streaming setup works before diving into complex files. Drive API gets weird with certain document structures during PDF conversion.