GMAIL API 获取附件 PDF 未正确呈现。我错过了什么?

问题描述 投票:0回答:1

我创建了一个小型概念验证来测试从 GMAIL API 检索 PDF 附件。我能够成功阅读电子邮件和附件。我能够从附件中提取数据,经过一些尝试和错误后,当我什至无法打开 PDF 时,我现在可以打开 PDF。但 PDF 被渲染为乱码。此外,我的收件箱中的原始 PDF 大小与以编程方式检索的 PDF 不同。 我觉得这和base64解码有关系。我用谷歌/SO搜索了这个,并尝试了一些技巧,但似乎没有任何效果。

在搜索 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));
});
node.js gmail gmail-api
1个回答
0
投票

在你的展示脚本中,做如下修改怎么样?

修改后的脚本:

来自:

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, '+');
    。因此,请测试有和没有它的两种模式。

另外,请修改如下。

来自:

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));
});

注:

  • 当我使用示例电子邮件测试上述修改时,我确认可以正确导出 PDF 文件。
  • 此修改后的脚本假设您的身份验证、消息 ID 和附件 ID 是有效值。请注意这一点。
© www.soinside.com 2019 - 2024. All rights reserved.