首页 > 解决方案 > GMAIL API NodeJs

问题描述

我已经建立了一个 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)

                
            }
        });
    }

标签: javascriptnode.jsgmail-apicheerio

解决方案


更新:工作解决方案。

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

推荐阅读