Faizy
Faizy

Reputation: 1

Google Apps Script to save Gmail attachments to Google Drive of only specific file types

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 = "[email protected]";// 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.

Upvotes: 0

Views: 1013

Answers (1)

Tanaike
Tanaike

Reputation: 201493

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:

Upvotes: 1

Related Questions