0

I would like help to resolve the error when executing this function.

file.next is not a function error

function myFunction() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet_bd = ss.getSheetByName('BD');
var numRows = sheet_bd.getLastRow();
var pdf = sheet_bd.getRange(numRows, 3).getValue();
var file = pdf.slice(33, 66);

//console.log(pdf.slice(33, 66));

     MailApp.sendEmail({
     to: 'email@email.com',   
     subject: "test", 
     body:"Test message",
     attachments: [file.next().getAs(MimeType.PDF)],

  });
  
}
  • what is the result of `var file = pdf.slice(33, 66);` ? Looks like it may be a file in drive info, is that right? – iansedano Jul 13 '21 at 07:15
  • the result is the id of a file that is on the drive which is in this format https://drive.google.com/open?id=1XwCesyVWp-WpYm8pNFkOiH663rNqHx2b – Alvim Silva Jul 13 '21 at 15:18

2 Answers2

1

In your snippet, file ultimately comes from getValue(), which doesn't return an iterator, so you cannot use the next() method.

If you're getting the link of the file, you need to use it to load the file with getFileById(). But to do that, you need to extract just the ID of the file from the URL.

Based on the above, you can modify your snippet to something like this:

function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet_bd = ss.getSheetByName('BD');
  var numRows = sheet_bd.getLastRow();
  var filename = sheet_bd.getRange(numRows, 3).getValue();
  var pdf = DriveApp.getFileById(filename.match(/[-\w]{25,}/))

  MailApp.sendEmail({
    to: 'email@email.com',
    subject: "test",
    body: "Test message",
    attachments: [pdf.getAs(MimeType.PDF)],

  });

}
mshcruz
  • 1,967
  • 2
  • 12
  • 12
  • I didn't understand perfectly Could you exemplify? At the end, I would like to send you a pdf file that is on my drive, which address is https://drive.google.com/open?id=1XwCesyVWp-WpYm8pNFkOiH663rNqHx2b – Alvim Silva Jul 13 '21 at 15:21
  • Sure, I added a sample code to the answer. – mshcruz Jul 14 '21 at 02:02
1

You have this string:

"drive.google.com/open?id=1XwCesyVWp-WpYm8pNFkOiH663rNqHx2b"

All this is right now is a string, not an object or a link. To get the file behind the link you need to use the Drive service, to get the file, and then get the blob of the file. You need the blob because the sendEmail method requires this.

let id = file.match(/id=.+/)[0].slice(3) // This extracts the id from the url.
let driveFile = DriveApp.getFileById(id)
let blob = driveFile.getBlob()

MailApp.sendEmail({
     to: 'email@email.com',   
     subject: "test", 
     body:"Test message",
     attachments: [blob],
  });

Reference

iansedano
  • 6,169
  • 2
  • 12
  • 24