【问题标题】:GMAIL API NodeJsGMAIL API NodeJs
【发布时间】:2026-01-08 20:40:02
【问题描述】:

我已经设置了一个 gmail api 服务来查询我的电子邮件。我的连接已建立,我只是想下载一个文件附件。我找到文件没有问题。我遇到的障碍是能够将文件下载到我的本地驱动器中,以便我可以使用 js 执行一些数据清理。我的代码如下。 fileAttachment.value 返回文件的名称,但我想下载 .htm 文档的内容。感谢您的帮助。

//This api call will fetch the mailbody.
      this.gmail.users.messages.get({
            'userId': this.me,
            'id': msgId
        }, (err, res) => {
            if(!err){
                // console.log(res.data.payload)
                
                // var htmlBody = base64.decode(body.replace(/-/g, '+').replace(/_/g, '/'));
                // var mailparser = new Mailparser();
                let body = res.data.payload.headers;

                let fileAttachment = body.find(r => r.name === 'Content-Disposition')

                console.log(fileAttachment.value)

                
            }
        });
    }

【问题讨论】:

    标签: javascript node.js gmail-api cheerio


    【解决方案1】:

    更新:工作解决方案。

        getMail(msgId, attachmentId, size,callback){
            //This api call will fetch the mailbody.
            this.gmail.users.messages.get({
                'userId': this.me,
                'id': msgId,
                'attachmentId': attachmentId,
                'size':size
            }, (err, res) => {
                if(!err){
                    // console.log(res.data.payload)
    
                    let getCurrentDate = new Date();
    
                    getCurrentDate = getCurrentDate.setDate(getCurrentDate.getDate()-1); 
    
                    getCurrentDate = new Date(getCurrentDate);
    
                    console.log(getCurrentDate)
                    
                    msgId = res.data.id;
                    
                    attachmentId = res.data.payload.body.attachmentId;
    
                    size = res.data.payload.body.size; 
                    
    
                    this.gmail.users.messages.attachments.get({
                        "userId": this.me,
                        "messageId": msgId,
                        "id": attachmentId
                    }).then(res => {
    
                        const buff = Buffer.from(res.data.data, 'base64');
    
                        fs.writeFileSync('./data/cooler-report.htm', buff)
    
                        console.log(`Cooler Report File for ${getCurrentDate} created!`)
    
                    }).catch(error => {
                        console.log(`Error converting file ${error}`)
                    })
                }
            });
        }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center