Antoni
Antoni

Reputation: 2189

Attach a file to a mail and send it

I have the following code, which tries to send a mail with a .pdf file attached. This .pdf is located in my Google drive.

var files = DriveApp.getFilesByName('file_test.pdf');
GmailApp.sendEmail(email, subject, message, {attachments:files[0]});

I've found that "getFilesByName" returns an array, so that's why I'm using files[0], but it's still not working. I don't know how to debug it, so when I'm testing my code, I am able to send the mail, but I receive it with no attached files.

Upvotes: 0

Views: 306

Answers (1)

Cameron Roberts
Cameron Roberts

Reputation: 7387

When you use getFilesByName you are receiving a FileIterator, so you should use the hasNext() and next() functions to retrieve your file.

var files = DriveApp.getFilesByName('file_test.pdf');
if(files.hasNext()){
  var file = files.next();
  GmailApp.sendEmail(email, subject, message, {attachments:file});
}

In the GmailApp docs, they use the getAs() function on the file to return it as a PDF, this may or may not be necessary in your case.

See:

https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)

https://developers.google.com/apps-script/reference/drive/drive-app

Upvotes: 1

Related Questions