I am trying to send an email attachment using the Drive API
and nodemailer's mailComposer
. I don't want to download the file from Google Drive so I'm doing this:
const attPDF = await drive.files.export(
{
fileId: "abcde123",
mimeType: "application/pdf",
},
{
responseType: "arrayBuffer",
}
);
Then I attach it to nodemailer like this:
const attachments = [
{
filename: "MyFile.pdf",
content: new Buffer.from(attPDF.data),
contentType: "application/pdf",
},
];
The email gets sent successfully, including the attachment, but the attachment is a blank page. It'll follow the amount of pages the original file has but it'll all be blank. If the file has 2 pages it'll show 2 blank pages. Does anyone know how to fix it?
I believe the exported PDF using arrayBuffer
produces an empty file, because arrayBuffer
processes files all at once and is limited to a specific length. This could result in a premature stoppage before the export finishes.
It is best to use stream
for the response type to process files in chunks which makes sure that all segments are processed once the export finishes. Since this will be a PDF that you are attaching it has to be encoded in base64.
For exporting Google Workspace documents:
const attPDF = await drive.files.export(
{
fileId: "abcde123",
mimeType: "application/pdf",
},
{
responseType: "stream",
}
);
For attachments:
const attachments = [
{
filename: "MyFile.pdf",
content: attPDF.data,
encoding: "base64",
contentType: "application/pdf",
},
];
Reference: