Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google apps script: Create a new document and send it using Gmail

I would like to create a document and then send it using Gmail. Here is my code:

function myFunction() {
var doc = DocumentApp.create('My document');
doc.getBody().appendParagraph('This is the file that i want to receive');
var file = DriveApp.getFileById(doc.getId());
GmailApp.sendEmail('[email protected]', 'Attachment example', 'Please see the attached        file.', {attachments: [file.getAs(MimeType.PDF)],name: 'Automatic Emailer Script'
 });
}

The file was created in my Google drive with the appended paragraph, the file id in doc.getId() is correct (using Logger.log() function). The problem is I always receive a blank pdf instead. I only could get the correct pdf file when change the code to manually input the file id in the : file = DriveApp.getFileById('1b-XpCUmmn020Vav6psp4aZnenyzyVCm6tcj1-TlvWyU');

What did i do wrong in the code? Thank you very much for your responses!

like image 755
Quan Nguyen Avatar asked Oct 22 '25 06:10

Quan Nguyen


1 Answers

Save the file before sending it. Also doc and DriveApp.getFileById(doc.getId()) actually refer to the same thing.

function myFunction() {
  var doc = DocumentApp.create('My document');
  doc.getBody().appendParagraph('This is the file that i want to receive');
  doc.saveAndClose();
  GmailApp.sendEmail('[email protected]', 'Attachment example', 'Please see the attached        file.', {attachments: [doc.getAs(MimeType.PDF)],name: 'Automatic Emailer Script' });
}
like image 151
Fabricator Avatar answered Oct 25 '25 13:10

Fabricator