I have the following script for sending emails in google sheets. "Email_Sent" is inserted in column 36 to prevent sending a duplicate email. For some reason the script repeats the sending of the email. Come someone please assist in telling me why the script isn't working as it should? Thanks
/**
* Sends emails from spreadsheet rows.
*/
function sendEmails() {
const ss = SpreadsheetApp.getActive();
const dsh = ss.getSheets()[0];//repl with getshbyname
const drg = dsh.getRange(2, 1, dsh.getLastRow() - 1, 36);
const vs = drg.getValues();
const tsh = ss.getSheets()[1];//repl with getshbyname
const tmpl = tsh.getRange('A1').getValue();
vs.forEach((r,i) => {
let emailSent = r[35];
let status = r[10];
if (status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT') {
MailApp.sendEmail(r[9], 'SUPERMIX QUOTATION',fillInTemplateFromObject(tmpl, r) );//if last paramenter is the options object then you are missing the null for the body. but since fillInTemplateFromObject is undefined I can not know that
dsh.getRange(2 i, 36).setValue('EMAIL_SENT');
SpreadsheetApp.flush();
}
});
}
/**
* Replaces markers in a template string with values define in a JavaScript data object.
* @param {string} template Contains markers, for instance ${"Column name"}
* @param {object} data values to that will replace markers.
* For instance data.columnName will replace marker ${"Column name"}
* @return {string} A string without markers. If no data is found to replace a marker,
* it is simply removed.
*/
function fillInTemplateFromObject(tmpl, data) {
var email = tmpl;
// Search for all the variables to be replaced, for instance ${"Column name"}
var templateVars = tmpl.match(/\$\{\"[^\"] \"\}/g);
// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var r = 0; templateVars && r < templateVars.length; r) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[r])];
email = email.replace(templateVars[r], variableData || '');
}
return email;
}
CodePudding user response:
Try this:
function sendEmails() {
const ss = SpreadsheetApp.getActive();
const dsh = ss.getSheets()[0];//repl with getshbyname
const drg = dsh.getRange(2, 1, dsh.getLastRow() - 1, 36);
const vs = drg.getValues();
const tsh = ss.getSheets()[1];//repl with getshbyname
const tmpl = tsh.getRange('A1').getValue();
vs.forEach((r,i) => {
let emailSent = r[35];
let status = r[10];
if (status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT') {
MailApp.sendEmail(r[?], 'SUPERMIX QUOTATION',fillInTemplateFromObject(tmpl, r) );//if last paramenter is the options object then you are missing the null for the body. but since fillInTemplateFromObject is undefined I can not know that
dsh.getRange(2 i, 36).setValue('EMAIL_SENT');
}
});
}
You code example has a few undefined variables and/or objects which make it impossible to provide a complete solution.