Divyesh Kanzariya Divyesh Kanzariya - 5 months ago 20
Javascript Question

How to get Gmail Attachment using JavaScript before send via GET request

Currently I am working on Chrome extension I want particular email (i.e message_id=1543c2a6347d984c) attachment data. I got email message_id also get attachment file name (i.e abc.zip) but how to get that attachment and send back to my server using Ajax.

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


Calling

var userId="xyz@gmail.com"
var message_id="1543c2a6347d984d";

getAttachments(userId,message_id,function callback(filename,minetype,attachment){

console.log('File Name is '+filename);
console.log('MimeType is '+minetype);
});


Error :
main.js:15 Uncaught TypeError: Cannot read property 'parts' of undefined (function getAttachments line 2)

Answer

Your message_id is a string, then you call getAttachments method and pass it as second parameter, in getAttachments, you call message.payload.parts, which means you want to get a property payload from a string, of course it is undefined.

Take a loot at Users.messages.get and Users.messages.attachments.get, you would need to first get the message, then get attachments from it.

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 getMessage(userId, messageId, callback) {
  var request = gapi.client.gmail.users.messages.get({
    'userId': userId,
    'id': messageId
  });
  request.execute(function(message) {
      callback(userId, message);
  });
}

var userId="xyz@gmail.com"
var message_id="1543c2a6347d984d";

getMessage(userId, message_id, function(userId, message) {
    getAttachments(userId, message, function(filename,minetype,attachment) {
        console.log('File Name is '+filename);
        console.log('MimeType is '+minetype);   
    });
});