Home > OS >  Appscript Gmail PDF not attached but showing [object][Object] instead
Appscript Gmail PDF not attached but showing [object][Object] instead

Time:04-15

I followed a tutorial here: https://www.youtube.com/watch?v=EpZGvKIHmR8.

The script below creates a PDF upon a google form submit and sends the PDF to a specified email address.

Everything works except that instead of the PDF being attached, the email is sent without a PDF, with the words [object Object] in the email body and I have no idea why!

Also a second problem: 2 PDF files are being created for every 1 form submission. Can anyone solve this too?

Here is my code:

function afterFormSubmit(e) {
  const info = e.namedValues;
  const pdfFile = createPDF(info);
  createPDF(info);
  sendEmail(e.namedValues['Your Email Address'][0],pdfFile);
}

function sendEmail(email, pdfFile){
  console.log(pdfFile);
  GmailApp.sendEmail(email,"here is your PDF",{
    attachments:[pdfFile],
    name: "My Name"
  });

}

function createPDF(info){
   const pdfFolder = DriveApp.getFolderById("112350000ffedfef");
   const tempFolder = DriveApp.getFolderById("24355kknflef");
   const templateDoc = DriveApp.getFileById("343kndwlkncv");

   const newTempFile = templateDoc.makeCopy(tempFolder);

   const openDoc = DocumentApp.openById(newTempFile.getId());
   const body = openDoc.getBody();

   for (var key in info){
     const texttoreplace = "{{" key "}}";
     body.replaceText(texttoreplace,info[key][0]);
   }

   openDoc.saveAndClose();
  
   const blobPDF = newTempFile.getAs(MimeType.PDF);
   const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Date of Meeting'][0]   " "   info['Company Name'][0]); 
   
   return pdfFile;

}

CodePudding user response:

The arguments of GmailApp.sendEmail(recipient, subject, body, options) are recipient, subject, body, options. When I saw your script, you use GmailApp.sendEmail(email,"here is your PDF",{attachments:[pdfFile], name: "My Name"}).

In this case, options is used as body. I thought that this is the reason of your issue. In order to remove this issue, how about the following modification?

From:

GmailApp.sendEmail(email,"here is your PDF",{
  attachments:[pdfFile],
  name: "My Name"
})

To:

GmailApp.sendEmail(email, "here is your PDF", "sample text body", {
  attachments: [pdfFile],
  name: "My Name"
});

Or,

MailApp.sendEmail({
  to: email,
  subject: "here is your PDF",
  attachments: [pdfFile],
  name: "My Name",
  // body: "sample text body" // If you want to use.
})

References:

  • Related