简体   繁体   English

通过电子邮件将Google文档作为PDF附件发送

[英]email Google Doc as PDF attachment

abc@example.comAfter struggling for a while with this I am calling for help from the crowd. 经过一段时间的努力后,我呼吁人群中的帮助。

I am trying to attach 2 Google Docs to an email as PDFs. 我正在尝试将2个Google文档作为PDF附加到电子邮件中。 I see many examples in regard to Google Sheets and have successfully been able to email copies of sheets as PDF, but I have not been able to port this over to Docs. 我看到了许多有关Google表格的示例,并且已经能够通过电子邮件成功地将表格的副本以PDF格式发送,但是我无法将其移植到文档中。

In multiple different scenarios, the PDF attachments are either a copy of my original template Doc or an image capture of "One Account. All of Google" sign in page . 在多种情况下,PDF附件要么是我原始模板Doc的副本,要么是“一个帐户。全部Google”登录页面的图像捕获。 When I look at the links that are generated (Logger.log) and use them, a copy of the correct Doc is downloaded. 当我查看生成的链接(Logger.log)并使用它们时,将下载正确的文档的副本。

Below is an example of my scenario in which I am trying to create the email attachments. 以下是我尝试创建电子邮件附件的情况的示例。 See function emailDocAsPDF() towards the bottom 参见底部的函数emailDocAsPDF()

Thanks in advance for any guidance on this issue. 在此先感谢您提供有关此问题的任何指导。

function myFunctionUpdated() {

  var testTemplateId = searchDriveFile('Test Template');
  Logger.log('test template id = ' + testTemplateId);

  var fileName = 'Copy of Test Template'
  Logger.log(fileName);

  DriveApp.getFileById(testTemplateId).makeCopy(fileName);

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = ss.getRange(1, 1, 3, 2).getValues();

  var copyNewTemplateId = searchDriveFile(fileName);

  var copyTemplate = DocumentApp.openById(copyNewTemplateId);
  var copyTemplateBody = copyTemplate.getBody().editAsText();

  for (i=0; i<range.length; i++) {
      copyTemplateBody.replaceText(range[i][0], range[i][1]);
  }

  copyTemplate.saveAndClose();

  emailDocAsPDF(fileName)
}


// Searched Google Drive for a file name and returns the file ID.
function searchDriveFile(fileName) {
  var files = DriveApp.searchFiles(
     'title = "'+ fileName +'"');
  while (files.hasNext()) {
    var file = files.next();
    var id = file.getId();
    return id;
  } 
}


// Send document in an email as PDF
function emailDocAsPDF(fileName) {

  var staticDoc = 'FILE-ID';

  var attachmentDoc = UrlFetchApp.fetch("https://docs.google.com/document/d/" + copyTemplateId + "/export?format=pdf");
  Logger.log("https://docs.google.com/document/d/" + copyTemplateId + "/export?format=pdf");

  var attachmentStaticDoc = UrlFetchApp.fetch("https://docs.google.com/document/d/" + staticDoc + "/export?format=pdf");
  Logger.log("https://docs.google.com/document/d/" + staticDoc + "/export?format=pdf");

  var fileBlob = [];

  fileBlob[0] = attachmentDoc.getBlob().getAs('application/pdf');
  fileBlob[1] = attachmentStaticDoc.getBlob().getAs('application/pdf');

  var body = "Bird is the WORD!! <br>" +
    "<a href='http://www.example.com'>Visit Example</a>";

   if (MailApp.getRemainingDailyQuota() > 0) 
    GmailApp.sendEmail("email@example.com", "Test Documents Email", body, {
      htmlBody: body,
      attachments:[fileBlob[0],fileBlob[1]]     
    });

}

EDIT -- Successful Updates with code provided by Sandwich. 编辑 -使用Sandwich提供的代码成功更新。

// Send document in an email as PDF
function emailDocAsPDF(fileName) {

  var staticDoc = 'FILE-ID';

  var copyTemplateId = searchDriveFile(fileName);

  var blobs = [];

  var doc = DriveApp.getFileById(copyTemplateId);
  blobs[0] = doc.getBlob().getAs('application/pdf').setName('MyAttachment1.pdf');

  var doc = DriveApp.getFileById(staticDoc);
  blobs[1] = doc.getBlob().getAs('application/pdf').setName('MyAttachment2.pdf');

  var zipBlob = Utilities.zip(blobs).setName('Documents.zip');

  var recipient = 'abc@example.com';
  var subject = 'Test Email';
  var body = 'Bird is the WORD';
  MailApp.sendEmail(recipient, subject, body, {attachments: [zipBlob]});
}

To attach any kind of document as a PDF, call getBlob on the file, specify content type as with .getAs('application/pdf') and optionally set a name with setName . 要将任何类型的文档附加为PDF,请在文件上调用getBlob ,使用.getAs('application/pdf')指定内容类型,并可以选择使用setName设置名称。 That's all: 就这样:

var doc = DriveApp.getFileById('ID_HERE');
var blob = doc.getBlob().getAs('application/pdf').setName('MyAttachment.pdf');
var recipient = 'user@example.com';
var subject = 'Email subject';
var body = 'Text here';
MailApp.sendEmail(recipient, subject, body, {attachments: [blob]});

You were trying to use "export as PDF via URL query", which is a poorly documented feature that is sometimes useful for Sheets (setting the boundaries of exported region), but is unnecessary for Docs, if it even exists for them. 您正在尝试使用“通过URL查询导出为PDF”,这是一个记录较差的功能,有时对“工作表”(设置导出区域的边界)有用,但对文档则没有必要,即使它们存在。 The above method should work for any kind of content stored in Google Drive. 上述方法适用于存储在Google云端硬盘中的任何内容。

By the way, it is preferable to use MailApp instead of GmailApp when sending email, because it keeps the level of authorization to what you need: sending emails. 顺便说一句,在发送电子邮件时,最好使用MailApp而不是GmailApp ,因为它可以保持所需的授权级别:发送电子邮件。 With GmailApp , the script is also granted permission to access and delete all of your existing emails, which is unadvisable for scripts composed by trial, error, and copying code from the Internet. 借助GmailApp ,该脚本还被授予访问和删除所有现有电子邮件的权限,这对于由试用,错误和从Internet复制代码组成的脚本不建议使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM