我正在尝试复制驱动器中的文档,对其进行编辑并将其邮寄。基本上就像邮件合并。
我获取模板文档,制作副本,编辑副本,然后通过电子邮件发送。不幸的是,在电子邮件代码运行之前,编辑尚未完成,因此电子邮件在进行编辑之前会附加复制的文档。有没有解决的办法?
//make a copy of the template
var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile', DriveApp.getFolderById(targetFolderID));
//select the contents of the template
var copyBody = DocumentApp.openById(templateCopy.getId())
//replace text: set the date
copyBody.replaceText("%DATE%",'today')
//send email - the email that arrives does not have the date substitution, it still contains the %DATE% tag
GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {attachments:[copyBody.getAs(MimeType.PDF)]});
有关可能重复项的编辑:SpreadsheetApp.flush()与我们无关,因为我们不使用电子表格。
使用saveAndClose()
的DocumentApp
方法强制更改,然后继续。
根据Apps脚本文档:
保存当前的
Document
。导致刷新并应用待处理的更新。
saveAndClose()
方法在脚本执行结束时自动为每个打开的可编辑Document
调用。关闭的
Document
无法编辑。使用DocumentApp.openById()
重新打开给定的文档进行编辑。
function documentStuff() {
//make a copy of the template
var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile',
DriveApp.getFolderById(targetFolderID)
);
//select the contents of the template
var copyBody = DocumentApp.openById(templateCopy.getId());
//replace text: set the date
copyBody.replaceText("%DATE%",'today');
copyBody.saveAndClose();
sendMail(targetAddress, DocumentApp.openById(templateCopy.getId()));
}
function sendMail(targetAddress, file) {
//send email - the email that arrives does not have the date substitution
// it still contains the %DATE% tag
GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {
attachments: [
file.getAs(MimeType.PDF)]
}
);
}
将Document和Gmail方法拆分为单独的功能也可以帮助解决此问题。
DocumentApp
DocumentApp