0

I am trying to use Google Apps Script to automate downloading attachments from a Gmail inbox to a specific folder on the account's Google Drive using label. I found the code below that does that part well, but I need to modify it to save only specific file type. So please help me how to save only specific file type i.e .xlsx.

// copying-gmail-attachments-to-google-drive-using-apps-script
function saveAttachmentInFolder(){
 var folder = DriveApp.getFolderById('1cqkjQWj2QkT7TyvllHI7YJFfWNcEupW0');// your Google Drive Folder ID to save the files
 var userId = "acoounts.mfc66@gmail.com";// your email.I mean your own Gmail to
 var query = "label:Thrive_from april 2022 till 20th jan 2023";// the label you created to fetch attachments from
 var res = Gmail.Users.Messages.list(userId, {q: query});//The searching and using the results; never mind
 res.messages.forEach(function(m){
   var attA=GmailApp.getMessageById(m.id).getAttachments();
   attA.forEach(function(a){
     folder.createFile(a.copyBlob()).setName(a.getName()); // gets name of file
   });
 });
}
// end of script

Thanks in advance for your help.

1 Answer 1

1

In your situation, how about checking the mimeType of the data as follows?

From:

var attA=GmailApp.getMessageById(m.id).getAttachments();

To:

var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL);

or, if you want to check both mimeType and the extension of the filename, how about the following modification?

var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL || (/\.pdf$/i).test(a.getName());
  • When this modified script is used, the attachment files are filtered by the mimeType of XLSX format.

References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.