dbr0wn11
dbr0wn11

Reputation: 43

Google Apps Script: Saving Gmail Attachment to Google Drive

I'm fairly close to completing my Google Apps script project, which is parsing a simple 2 line Email and adding the attachment link (Attachment saved to Google Drive) to Google Sheets.

I'm stuck on saving the Email attachment to Google Drive. The code that is commented out is the block that's not working correctly. I took an example from: Save Gmail attachments on Google Drive -- But it doesn't seem to work for me.

Attached is my full code.

function parseEmailMessages() {

  var threads = GmailApp.search('label:test',0,100);
  var sheet = SpreadsheetApp.openById('<<SHEET ID>>');
  var folder = DriveApp.getFolderById('<<FOLDER ID>>');
  var testLabel = GmailApp.getUserLabelByName('test');
  var doneLabel = GmailApp.getUserLabelByName('finished');

  for (var i = 0; i < threads.length; i++) {
    var message = threads[i].getMessages();
    for (var j in message) {
      var content = message[j].getPlainBody();

      /*
      var attachments = threads[j].getAttachments();
      for (var k in attachments) {
      var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
        if (!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
        var file = DriveApp.createFile(attachmentBlob);
      }
      */

    }

    var [name, date] = content.split("\n");    

    function latestFile() {
      var gDriveFolder = DriveApp.getFolderById('<<FOLDER ID>>');
      var gDriveFile = gDriveFolder.getFiles();
      var lastFileId = gDriveFile.next().getId(); 
      return lastFileId.toString();
    }

    var urlStart = 'https://drive.google.com/a/<<DOMAIN>>/file/d/';
    var urlString = latestFile();
    var urlEnd = '/view?usp=drivesdk';    
    var pic = urlStart + urlString + urlEnd;

    sheet.appendRow([name,date,pic]);

    threads[i].removeLabel(testLabel);
    threads[i].addLabel(doneLabel);

  }
}

The error I receive is: "TypeError: Cannot find function getAttachments in object GmailThread."

It's true that getAttachments does not seem to be part of GmailThread in the documentation, but I'm not sure how to achieve my goal at the moment.

Upvotes: 3

Views: 4273

Answers (2)

ellaqezi
ellaqezi

Reputation: 41

var results = Gmail.Users.Messages.list(userId, {q: query});
results.messages.forEach(function (m) {
    var msg = GmailApp.getMessageById(m.id);
    msg.getAttachments().forEach(function (a) {
        var fileName = a.getName();
        fileName = saveAttachmentToFolder(folder, a, fileName, msg.getDate(), input.tz);
    });
});
function saveAttachmentToFolder(folder, attachment, fileName, date, timezone) {
    if (timezone) {
        fileName = standardizeName(attachment, date, timezone);
    }
    Logger.log(fileName);
    folder.createFile(attachment.copyBlob()).setName(fileName);
    return fileName;
}

The code snippet above is from a Gmail add-on that I created, specifically for saving attachments to Drive: https://github.com/ellaqezi/archiveByLabel/blob/main/Code.gs#L24

In the label field, you can define nested directories to create in Drive e.g. foo/bar.

In the query field, you can copy the parameters as you would use them in Gmail's search bar.

Upvotes: 0

Tanaike
Tanaike

Reputation: 201378

getAttachments() is not the method of Class GmailThread. So how about the following modification?

From:

var attachments = threads[j].getAttachments();

To:

var attachments = message[j].getAttachments();

Reference:

If this was not the direct solution, I apologize.

Upvotes: 1

Related Questions