Node.js调用Gmail API下载邮件.htm附件内容问题求助
你当前的代码仅读取了附件的元信息头,未获取附件实际内容,需要先提取附件ID调用Gmail专属的附件拉取接口,解码后存储到本地,完整实现如下:
Node.js 环境实现(适配本地存储+后续数据清洗需求)
const fs = require('fs'); // 原有邮件查询逻辑保持不变 this.gmail.users.messages.get({ userId: this.me, id: msgId }, (err, res) => { if (err) return console.error('邮件查询失败:', err); // 定位附件所在的payload块,有效附件会携带attachmentId字段 const attachmentPart = res.data.payload.parts.find(part => part.filename && part.body?.attachmentId ); if (!attachmentPart) return console.log('未匹配到有效附件'); // 提取附件文件名,和你原有逻辑衔接 const contentDisposition = res.data.payload.headers.find(r => r.name === 'Content-Disposition'); const fileName = contentDisposition?.value?.match(/filename="?([^"]+)"?/)?.[1] || attachmentPart.filename; // 调用Gmail附件接口拉取实际内容 this.gmail.users.messages.attachments.get({ userId: this.me, messageId: msgId, id: attachmentPart.body.attachmentId }, (attachErr, attachRes) => { if (attachErr) return console.error('附件拉取失败:', attachErr); // 转换Base64URL编码为Buffer写入本地 const base64Content = attachRes.data.data.replace(/-/g, '+').replace(/_/g, '/'); const fileBuffer = Buffer.from(base64Content, 'base64'); fs.writeFile(`./${fileName}`, fileBuffer, writeErr => { if (writeErr) return console.error('本地写入失败:', writeErr); console.log(`附件${fileName}已保存到当前目录,可直接读取做数据清洗`); }); }); });
浏览器环境下载实现(无需本地文件系统权限)
如果是在前端页面运行,把上述代码中fs.writeFile部分替换为以下逻辑即可触发浏览器自动下载:
const base64Content = attachRes.data.data.replace(/-/g, '+').replace(/_/g, '/'); const uint8Array = Uint8Array.from(atob(base64Content), c => c.charCodeAt(0)); const blob = new Blob([uint8Array], { type: 'text/html' }); const downloadLink = document.createElement('a'); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); URL.revokeObjectURL(downloadLink.href);
内容的提问来源于stack exchange,提问作者sjorjano
相关产品推荐
相关产品推荐

