如何在创建 PDF 后通过 google 脚本发送电子邮件和加密

How to send email and encrypt by google scripts after creating a PDF

我使用此代码在客户填写表格后立即创建 pdf 文件:

function After_Submit(e){
  
  const info = e.namedValues;
  Create_PDF(info);  
  
  console.log(info);
  

}

function Create_PDF(info) {
  
  const PDF_folder = DriveApp.getFolderById("folder id");
  const TEMP_Folder = DriveApp.getFolderById("folder id");
  const PDF_Template = DriveApp.getFileById("pdf temp id");
  
  const newTempFile = PDF_Template.makeCopy(TEMP_Folder);
  const  OpenDoc = DocumentApp.openById(newTempFile.getId());
  const body = OpenDoc.getBody();
  
  console.log(body);
  
   body.replaceText("{Code}", info['Code'][0]);
   body.replaceText("{Date}", info['Date'][0]);
   body.replaceText("{Name}", info['Name'][0]);
   body.replaceText("{Birthdate}", info['Birthdate'][0])
   body.replaceText("{Address}", info['Address'][0]);
   OpenDoc.saveAndClose();
  
  const BLOBPDF = newTempFile.getAs(MimeType.PDF);
  PDF_folder.createFile(BLOBPDF).setName(info['Name'][0] + " " + info['Code'][0]);
  console.log("PDF created");
  TEMP_Folder.removeFile(newTempFile);

}

显然我还使用了触发器来自动化它。

现在我需要创建一个功能,将该 pdf 发送到客户在表单上提供的电子邮件中,并使用他的生日“例如”作为密码来保护它!

有人可以帮忙吗?

非常感谢

不幸的是,Apps Script 没有任何在 PDF 文件中设置密码的特定特性或功能,要实现这样的功能,您需要使用第三方应用程序、API 或库。

要发送带附件的电子邮件,您可以使用方法 MailApp.sendEmail,如下所示(以下代码段包含自解释注释):

function Create_PDF(info) {
  
  const PDF_folder = DriveApp.getFolderById("folder id");
  const TEMP_Folder = DriveApp.getFolderById("folder id");
  const PDF_Template = DriveApp.getFileById("pdf temp id");
  
  const newTempFile = PDF_Template.makeCopy(TEMP_Folder);
  const  OpenDoc = DocumentApp.openById(newTempFile.getId());
  const body = OpenDoc.getBody();
  
  console.log(body);
  
   body.replaceText("{Code}", info['Code'][0]);
   body.replaceText("{Date}", info['Date'][0]);
   body.replaceText("{Name}", info['Name'][0]);
   body.replaceText("{Birthdate}", info['Birthdate'][0])
   body.replaceText("{Address}", info['Address'][0]);
   OpenDoc.saveAndClose();
  
  const BLOBPDF = newTempFile.getAs(MimeType.PDF);
  
///////////////////////// MODIFICATION ////////////////////////////////

  // Get the file you want to send as an attachment
  var file = PDF_folder.createFile(BLOBPDF).setName(info['Name'][0] + " " + info['Code'][0]);
  
    // Send email using the function sendEmail of MailApp (recipient, subject, message, options)
    MailApp.sendEmail('mike@example.com', 'Attachment example', 'PDF attached', {
    name: 'Attached file',
    attachments: [file.getAs(MimeType.PDF)]
    });

/////////////////////////////////////////////////////////////////////////
    
  console.log("PDF created");
  TEMP_Folder.removeFile(newTempFile);
  
}