Reputation: 536
So, I recently have been working on a project with google sheets, where I am getting some data and creating files with that data to email as attachment. I am
function sendEmail(){
for (var row in rangeData) {
var varify = false;
var fileName = new Date().toString();
Logger.log("template " + templateId);
var fileId = DriveApp.getFileById(templateId).makeCopy().getId();
DriveApp.getFileById(fileId).setName(fileName);
var body = DocumentApp.openById(fileId).getBody();
Logger.log('current row ' + rangeData[row]);
for (var column in rangeData[row]) {
var target = firstRowMapped.indexOf(columnNames[column]);
if (target != -1) {
Logger.log('found Key');
try {
body.replaceText(firstRowMapped[target].toString(), rangeData[row]
[target].toString());
varify = true;
} catch (err) {
Logger.log(err);
}
}
}
if (varify == true) {
var toSend = DocumentApp.openById(fileId);
// send mail
try {
MailApp.sendEmail(rangeData[row][emailColumn], 'Test Email', rangeData[row][0], {
name: 'Emailer Script from DOER',
cc: rangeData[row][ccColumn],
attachments: toSend.getAs(MimeType.PDF)
});
Logger.log('sent');
} catch (err) {
Logger.log(err);
}
}
}
}
I am getting my expected files on google drive. The Id of those files match that of toSend
yet when I am getting my email, I get the fileId
. I have been trying to figure this out for days, no luck. Does anyone know why this might be happening? Any Ideas? I personally have send countless attachments through this process (not with a template though) and never had this problem.
Upvotes: 1
Views: 69
Reputation: 4979
The code in the question is opening two instances of the file, modifying one, then sending the other (unmodified) instance. To fix this, you can either:
Save and close the first instance before opening the other
/* globals
rangeData, templateId, firstRowMapped,columnNames, emailColumn, ccColumn */
function sendEmail() {
...
var doc = DocumentApp.openById(fileId);
var body = doc.getBody();
...
doc.saveAndClose();
if (varify == true) {
var toSend = DocumentApp.openById(fileId);
// send mail
...
}
Or, only open one instance, and send the same one you modified
// Don't close the doc before this
var toSend = doc;
Upvotes: 3
Reputation: 536
Reopening and saving fixed my errors.
var editFile = DocumentApp.openById(fileId);
var body = editFile.getBody();
var target = firstRowMapped.indexOf(columnNames[column]);
if (target != -1) {
Logger.log('found Key');
try {
Logger.log('row column ' + rangeData[row][target] + ' replacing ' +
firstRowMapped[target]);
body.replaceText(firstRowMapped[target].toString(), rangeData[row]
[target].toString());
Logger.log('replaced Key');
varify = true;
editFile.saveAndClose();
Upvotes: 1