Home > Software engineering >  Sending multiple attachments using Google Appscript and Google Sheet
Sending multiple attachments using Google Appscript and Google Sheet

Time:09-29

I have a program I use to send mails using data in Google Sheet and typing the file name in the column in Sheet. This was working fine as long as I had to send only one attachment.

However, now that I'm trying to send 2 attachments, I am not sure what change I need to make. I looked at other responses - where you specify two variables instead of one - however in my case, its not definitive whether I'll mail 1 or 2 or 3 attachments, so I require a solution which can work with n number of files.

Attaching my current code for reference:

var attach = ws.getRange(lr, 17).getValue();
var file1 = DriveApp.getFilesByName(attach).next();
GmailApp.sendEmail('',
""   sub   "",
'',
{htmlBody: htmlforemail,
bcc: emails.join(","),
attachments: file1
}

CodePudding user response:

If you look at the documentation you will see that the attachments parameter expects to receive an array of files. So just push the files you need there and that's it.

CodePudding user response:

Issue and solution:

If I understand your situation correctly, you want to send multiple Drive files as attachments in an email. The names of these files can be found in a single cell in your spreadsheet, in a comma-separated string.

In this case, as you can see in the documentation, the attachments parameter requires an array of BlobSource to be provided, with each element in this array corresponding to each file.

Therefore, you should do the following:

  • Split the comma-separated string into an array with the file names (see split).
  • For each file name, look for the file in Drive (using getFilesByName and next, as you are already doing). You can use map to transform the file names array to a files array.
  • Provide the resulting array as attachments.

Code snippet:

var attach = ws.getRange(lr, 17).getValue().split(",");
var files = attach.map(fileName => DriveApp.getFilesByName(fileName).next());
GmailApp.sendEmail(recipient, subject, '', {
  htmlBody: htmlforemail,
  bcc: emails.join(","),
  attachments: files
});
  • Related