如何使用带有Node.js的Gmail API下载附件?

时间:2018-07-06 19:09:17

标签: javascript node.js gmail-api

我正在尝试在执行此操作的本地计算机上创建一个节点应用程序:

1)查看我的Gmail收件箱。

2)如果电子邮件具有特定标签和附件,请下载它。

我在第2步。

我困惑的部分是关于“部分”的部分。

https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get

Google的示例代码:

function getAttachments(userId, message, callback) {
  var parts = message.payload.parts;
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    if (part.filename && part.filename.length > 0) {
      var attachId = part.body.attachmentId;
      var request = gapi.client.gmail.users.messages.attachments.get({
        'id': attachId,
        'messageId': message.id,
        'userId': userId
      });
      request.execute(function(attachment) { // <--- that attachment param
        callback(part.filename, part.mimeType, attachment);
      });
    }
  }
}

“附件”似乎包含附件数据。

这是我的代码:

const gmail = google.gmail({version: 'v1', auth});

gmail.users.messages.list({
  userId: 'me',
  'q':'subject:my-test has:nouserlabels has:attachment'
}, (err, res) => {
  if (err) return console.log('1 The API returned an error: ' + err);

  const msgs = res.data.messages;

  if(typeof msgs !== 'undefined'){
    console.log('Messages:');
    msgs.forEach( msg => {

      console.log(`- ${msg.id}`);

      gmail.users.messages.get({
        userId: 'me',
        id: msg.id,
        format:'full'
      },(err, res) => {
        if (err) return console.log('2 The API returned an error: ' + err);

        // Wheres the data????? //

        console.log('A')
        console.log(res.data.payload.parts)

        console.log('B')
        console.log(res.data.payload.parts[1])

        console.log('C')
        console.log(res.data.payload.parts[1].body)
      })
    });
  } else {
    console.log('no messages found')
  }


});

1 个答案:

答案 0 :(得分:1)

对于每封邮件,您可以使用part.body.attachmentId使用gmail.users.messages.attachments.get进行Gmail API调用。

以下是一个函数,该函数返回带有附件大小和base64编码附件的JSON对象。我意识到它现在有点混乱,我仍在完善它。我离开了console.logs,以防您可能想进一步检查对象。您也应该可以将gmail.users.messages.list查询添加到我的函数中。

您可以在此处使用npm软件包保存这些文件,以保存附件文件,例如https://www.npmjs.com/package/base64-to-image

function listMessagesWithAttachments(auth, callback) {
    const gmail = google.gmail({version: 'v1', auth})
    console.log('list messages with attachments auth: ' + JSON.stringify(auth))
    gmail.users.messages.list({
      userId: 'me',
      maxResults: 5
    }, (err, {data}) => {
      if (err) return console.log('Error in listMessageswithAttachments, messages list: ' + err)
      let dataForExpress = []
      let messages = data.messages
      messages.forEach(function (message, index) {
        gmail.users.messages.get({
          userId: 'me',
          id: data.messages[index].id,
          format: 'full'
        }, (err, {data}) => {
          if (err) return console.log('Error: ' + err)
            //console.log('data to push: ' + data)
            //console.log('messages.length: ' + messages.length)
            dataForExpress.push(data)
            if (dataForExpress.length == messages.length) {
              let attachmentIds = []
              let attachments = []
                dataForExpress.forEach(function(message, index) {
                    //console.log('message number: ' + index)
                    //console.log(message.payload.parts)
                    let messagePayloadParts = message.payload.parts 
                    if (messagePayloadParts.length > 0) {
                        messagePayloadParts.forEach(function (part, j) {
                        //console.log('messageId: ' + JSON.stringify(message.id))
                        //console.log('message parts partId ' + JSON.stringify(part.partId))
                        //console.log('mime-type ' + JSON.stringify(part.mimeType))
                        //console.log('filename ' + JSON.stringify(part.filename))
                            let object = {}
                            if (part.body.size && part.body.size > 0 && part.body.attachmentId) {
                                //console.log('messageId: ' + JSON.stringify(part.partId))
                                //console.log('attachmentId ' + JSON.stringify(part.body.attachmentId))
                                let object = {"index": `${j}`, "messageId": message.id, "attachmentId": part.body.attachmentId}
                                attachmentIds.push(object)
                            }
                            if (dataForExpress.length - 1 == index) {
                                attachmentIds.forEach(function (attachment, kindex) {
                                    gmail.users.messages.attachments.get({
                                        userId: 'me',
                                        messageId: attachment.messageId,
                                        id: attachment.attachmentId
                                    }, (err, {data}) => {
                                        if (err) return console.log('Error getting attachment: ' + err)
                                        //console.log('attachment' + JSON.stringify(data))
                                        attachments.push(data)
                                        if (attachmentIds.length == attachments.length){
                                        console.log('callback: ' + JSON.stringify(attachments))
                                        callback(attachments)
                                        }
                                    })
                                })   
                            }
                        })                               
                    }              
                })
            }
        })
        })
    })
}