I have created a small Proof of Concept to test retrieving PDF attachments from GMAIL API. I am able to successfully READ both Emails and Attachments. I am able to pull the data from attachments and after some trial and error when I was unable to even open the PDFs, I'm now able to open PDFs. But the PDFs are being rendered as garbled. Also the original PDF in my inbox size is different from the programmatically retrieved PDF. I feel this has something to do with the base64 decoding. I did google/SO search this, and tried a few tricks but nothing seems to be working.
While searching SO, it was suggested to use the trick in the decodeBase64
function to get PDF's to work. I've included it in my code below but it didn't work either.
This is the code that successfully pulls the PDF attachment and writes it to the local filesystem. But the PDF attachment size is different from one in my inbox and it opens up garbled. Any suggestions?
const Base64 = require('js-base64')
......
// Successfully pulls attachments
async function getAttachment(messageId, attachmentId, auth) {
const response = await google.gmail('v1').users.messages.attachments.get({
auth: auth,
userId: 'me',
messageId: messageId,
id: attachmentId
});
return response.data;
}
// Stack Overflow suggestion to fix PDF. It fixed "Unable to Open" file but PDF is still garbled.
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+') // important line
return Base64.atob(str)
}
// Working code to pull messages with attachments from GMAIL code hidden for brevity
....
....
getAttachment(messageId, attachmentId, auth).then(attachmentBufferData => {
fs.writeFile(part.filename, decodeBase64(attachmentBufferData.data));
});
In your showing script, how about the following modification?
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+') // important line
return Base64.atob(str)
}
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+');
return Buffer.from(str, "base64");
}
str = str.replace(/_/g, '/').replace(/-/g, '+');
might not be required to be used. So, please test both patterns with and without it.And also, please modify as follows.
getAttachment(messageId, attachmentId, auth).then(attachmentBufferData => {
fs.writeFile(part.filename, decodeBase64(attachmentBufferData.data));
});
getAttachment(messageId, attachmentId, auth).then((attachmentBufferData) => {
fs.writeFileSync(part.filename, decodeBase64(attachmentBufferData.data));
});