Copying Gmail attachments to Google Drive using Apps Script

Viewed 5297

I am using Google Apps Script to automate saving attachments from emails to unique Google Drive folders depending on the Label the messages have been filtered into.

So far I have managed to get the message ID using some code snippet I have found on line. However I am stuck trying to access the body of the messages & save the attachment to drive folders.

function getMessage(){
     var folder = DriveApp.getFolderById('xxxxxxxxxxxxx');
     var userId = "myemail@gmail.com";
     var query = "label:Global Alcohol";
     var res = Gmail.Users.Messages.list(userId, {q: query});
     var attachment = msgs.Attachments.get(userId, messageId, id);
     var ids = res.messages.map(function(e){return e.id});
     Logger.log(ids);// Message IDs with the specific labels.
     }

Thanks in advance for your help.

2 Answers

Try this:

function saveAttachmentInFolder(){
  var folder = DriveApp.getFolderById('xxxxxxxxxxxxx');
  var userId = "myemail@gmail.com";
  var query = "label:Global Alcohol";
  var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
  res.messages.forEach(function(m){
    var attA=GmailApp.getMessageById(m.id).getAttachments();
    attA.forEach(function(a){
      var ts=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyMMddHHmmss");
      folder.createFile(a.copyBlob()).setName(a.getName()+ts);
    });
  });
}
var query = 'label:global-alcohol'; 
var folder = 'Global Alcohol';
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 based on a Gmail add-on that I created, specifically for saving attachments to labeled folders in 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.

Related