无法读取未定义的属性“部分”

时间:2017-10-05 15:10:56

标签: javascript

你好,我想使用gmail api,但我得到下一个错误

无法读取未定义的属性“部分”

当我尝试从gmail电子邮件中获取附件时,这是我的代码来自gmail api expamles,我尝试发送

  getAttachments('me',message.id , avCallBack);  AND   getAttachments('me',message , avCallBack);

但这不起作用,请帮助我,我希望从我的电子邮件下载文件与api google javascript

  function displayInbox() {
    var request = gapi.client.gmail.users.messages.list({
      'userId': 'me',
      'labelIds': 'INBOX',
      'maxResults': 15
    });
    request.execute(function(response) {
      $.each(response.messages, function() {
        var messageRequest = gapi.client.gmail.users.messages.get({
          'userId': 'me',
          'id': this.id
        });
        console.log("---"+JSON.stringify(messageRequest));
        messageRequest.execute(appendMessageRow);

      });
    });
  }

   function appendMessageRow(message) {
       getAttachments('me',message.id , avCallBack);

    $('.table-inbox tbody').append(
      '<tr>\
        <td>'+getHeader(message.payload.headers, 'From')+'</td>\
        <td>\
          <a href="#message-modal-' + message.id +
            '" data-toggle="modal" id="message-link-' + message.id+'">' +
            getHeader(message.payload.headers, 'Subject') +
          '</a>\
        </td>\
        <td>'+getHeader(message.payload.headers, 'Date')+'</td>\
      </tr>'
    );

    function getHeader(headers, index) {
    var header = '';
    $.each(headers, function(){
      if(this.name === index){
        header = this.value;
      }
    });
    return header;
      }
  }


  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) {
          callback(part.filename, part.mimeType, attachment);
        });
      }
    }
  }

  function avCallBack(name, mimetype, filee){
      alert ("->" + name + mimetype + file);
  }

1 个答案:

答案 0 :(得分:0)

您正在将message.id传递给getAttachments函数。根据{{​​3}} message.id是一个字符串。在getAttachments中,您从payload对象获得message,因为您传递了字符串,所以没有它。您需要传递Users.messages个对象。

问题还在于使用$.each。为什么不使用forEach?请参阅以下示例:

 response.messages.forEach(function(msg) {
    var messageRequest = gapi.client.gmail.users.messages.get({
      'userId': 'me',
      'id': msg.id
    });
    console.log("---"+JSON.stringify(messageRequest));
    messageRequest.execute(appendMessageRow);
 });