首页 > 解决方案 > 从表单提交发送 PDF 附件 - 脚本不起作用

问题描述

我使用了 youtube 上 LEARN GOOGLE SPREADSHEETS 建议的脚本。除了 sendEmail 功能外,所有功能都在工作——它现在让我发疯了……谁能看到我做错了什么?

function afterFormSubmit(e) {

    const info = e.namedValues;  
    const pdfFile = createPDF(info);
    const entryRow = e.range.getRow();
    const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Responses");
  
    sendEmail(e.namedValues['Email address for your certificate'][0],pdfFile);

}


function sendEmail(email,pdfFile){
  
  GmailApp.sendEmail(email, "Your Heartstart Certificate", "Your certificate is attached.", {
    attachments: [pdfFile],
    name: 'Meon Valley Heartstart'
    });
  
}

function createPDF(info){

  const pdfFolder = DriveApp.getFolderById("1sVhEpamhLvhlfxHg61zF9rptri5Momm3");
  const tempFolder = DriveApp.getFolderById("1v7VF7MTV_hB-9PeLIWRr5MdR4Fa3IrZF");
  const templateDoc = DriveApp.getFileById("1dCv5B0zDqebm7ZRtT-qs7eWB_kLOKR8A-mKgeFdORv0");

  const newTempFile = templateDoc.makeCopy(tempFolder);
  
  const openDoc = DocumentApp.openById(newTempFile.getId());
  const body = openDoc.getBody();
  body.replaceText("{Name}", info['Your name as you want it to appear on your certificate'][0]);
  body.replaceText("{Date}", info['Date you completed the course'][0]);
  openDoc.saveAndClose();

  const blobPDF = newTempFile.getAs(MimeType.PDF);
  const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Your name as you want it to appear on your certificate'][0] + " " + info['Date you completed the course'][0]);
  tempFolder.removeFile(newTempFile);

}

标签: google-apps-script

解决方案


回答:

您需要从createPDF.

使固定:

行后:

const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Your name as you want it to appear on your certificate'][0] + " " + info['Date you completed the course'][0]);

添加:

return pdfFile.getBlob()

然后更改您的电子邮件发送电话:

GmailApp.sendEmail(email, "Your Heartstart Certificate", "Your certificate is attached.", {
  attachments: [pdfFile.getBytes()],
  name: "Meon Valley Heartstart",
  mimeType: "application/pdf"
  });

推荐阅读