简体   繁体   中英

Send email with attachment 'is not a function error'

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)],

  });
  
}

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)],

  });

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM