我已经创建了一个小的概念验证来测试从Gmail API检索PDF附件.我能够成功地阅读邮箱和附件.我能够从附件中提取数据,在经历了一些try 和错误后,我甚至无法打开PDF,现在我能够打开PDF了.但这些PDF文件被认为是乱码.此外,我收件箱大小中的原始PDF与以编程方式检索的PDF不同. 我觉得这和Base64解码有关.我做了谷歌搜索,try 了一些技巧,但似乎都不起作用.
在搜索SO时,建议使用decodeBase64
函数中的技巧来使PDF工作.我已经在下面的代码中包含了它,但它也不起作用.
这是成功提取PDF附件并将其写入本地文件系统的代码.但是PDF附件的大小和我收件箱里的不一样,打开时会乱码.有什么建议吗?
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));
});