Som odosielaní e-mailov s google listov pomocou šablóny

0

Otázka

Ja sa pokúšam spustiť skript nižšie odosielanie e-mailov zo šablóny v List[1] A1. Zakaždým, keď sa skript spustí, vyberie údaje pre fillInTheTemplate funkciu z rozsahu

const grg = sheet.getRange(2, 1, 6, 36); Som si vyžadujú kód vybrať iba v rozsahu pre fillTemplateFunction z riadok, ktorý má nemá "Email_Sent" v riadku 36

Vďaka za každú pomoc

 * 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() - 2, 36);
  const vs = drg.getValues();
  const tsh = ss.getSheets()[1];//repl with getshbyname
  const tmpl = tsh.getRange('A1').getValue();
  var sheet = SpreadsheetApp.getActiveSheet();
  const grg = sheet.getRange(2, 1, 6, 36);
  objects = getRowsData(sheet, grg);
  for (var i = 0; i < objects.length; ++i) {
  var rowData = objects[i];}
  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, rowData) );//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');
    }
  });
}

/**
 * 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, grg) {
  console.log('[START] fillInTemplateFromObject()');
  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 i = 0; templateVars && i < templateVars.length; ++i) {
    // normalizeHeader ignores ${"} so we can call it directly here.
    var variableData = grg[normalizeHeader(templateVars[i])];
    email = email.replace(templateVars[i], variableData || '');
  }
SpreadsheetApp.flush();
  return email;
}
/**
 * Iterates row by row in the input range and returns an array of objects.
 * Each object contains all the data for a given row, indexed by its normalized column name.
 * @param {Sheet} sheet The sheet object that contains the data to be processed
 * @param {Range} range The exact range of cells where the data is stored
 * @param {number} columnHeadersRowIndex Specifies the row number where the column names are stored.
 *   This argument is optional and it defaults to the row immediately above range;
 * @return {object[]} An array of objects.
 */
function getRowsData(sheet, range, columnHeadersRowIndex) {
  columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(range.getValues(), normalizeHeaders(headers));
}

/**
 * For every row of data in data, generates an object that contains the data. Names of
 * object fields are defined in keys.
 * @param {object} data JavaScript 2d array
 * @param {object} keys Array of Strings that define the property names for the objects to create
 * @return {object[]} A list of objects.
 */
function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}

/**
 * Returns an array of normalized Strings.
 * @param {string[]} headers Array of strings to normalize
 * @return {string[]} An array of normalized strings.
 */
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

/**
 * Normalizes a string, by removing all alphanumeric characters and using mixed case
 * to separate words. The output will always start with a lower case letter.
 * This function is designed to produce JavaScript object property names.
 * @param {string} header The header to normalize.
 * @return {string} The normalized header.
 * @example "First Name" -> "firstName"
 * @example "Market Cap (millions) -> "marketCapMillions
 * @example "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
 */
function normalizeHeader(header) {
  var key = '';
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == ' ' && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

/**
 * Returns true if the cell where cellData was read from is empty.
 * @param {string} cellData Cell data
 * @return {boolean} True if the cell is empty.
 */
function isCellEmpty(cellData) {
  return typeof(cellData) == 'string' && cellData == '';
}

/**
 * Returns true if the character char is alphabetical, false otherwise.
 * @param {string} char The character.
 * @return {boolean} True if the char is a number.
 */
function isAlnum(char) {
  return char >= 'A' && char <= 'Z' ||
    char >= 'a' && char <= 'z' ||
    isDigit(char);
}

/**
 * Returns true if the character char is a digit, false otherwise.
 * @param {string} char The character.
 * @return {boolean} True if the char is a digit.
 */
function isDigit(char) {
  return char >= '0' && char <= '9';
}```


google-apps-script google-sheets
2021-11-23 23:09:33
1

Najlepšiu odpoveď

1

Keď som videl váš skript, zdá sa, že váš skript sa odošle e-mailu kontrola stĺpec "K" (stĺpec je číslo 11) a v stĺpci "AJ" (stĺpec číslo je 36) s if (status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT') {}. A keď som videl váš vzorové Tabuľky, riadok, kde je číslo, ktoré nemá žiadnu hodnotu "EMAIL_SENT" v stĺpcoch "AJ" je 5. Ale, keď som videl stĺpci "K", no hodnota je existujúce. Tým sa status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT' vráti false. Táto e-mailová nie je odoslaná. Myslel som si, že to môže byť dôvodom, pre váš problém.

Ak chcete odoslať e-mail, keď stĺpci "AJ" nemá hodnotu "EMAIL_SENT", ako sa o tieto úpravy?

Od:

if (status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT') { 

K:

if (emailSent != 'EMAIL_SENT') {

Pridané:

Z týchto odpovedí,

Kód je odosielanie e-mailových ako som vyžadovať a "Email_Sent" je umiestnené v stĺpci AJ ako malo. Problém mám súvisí s funkciou fillInTemplateFromObject(tmpl, grg) funkciu. Rozsah ja používam pre túto funkciu je " const grg = list.getRange(2, 1, 5, 36); ' To začína rad 2 rady a zahŕňa 5 riadkov. Keď som odoslanie e-mailu bunky údaje v rozsahu pre šablónu údaje z riadku 6 aj keď riadok, ktorý Email_Sent je v riadku 4. Šablóna by mala prijať dáta z rovnakých buniek, ktoré e-mail sa posiela.

V tomto prípade, ako sa o tieto úpravy?

Od:

  for (var i = 0; i < objects.length; ++i) {
  var rowData = objects[i];}
  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, rowData) );//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');
    }
  });

K:

vs.forEach((r, i) => {
  let emailSent = r[35];
  if (emailSent != 'EMAIL_SENT') {
    MailAppaa.sendEmail(r[9], 'SUPERMIX QUOTATION', fillInTemplateFromObject(tmpl, objects[i]));
    dsh.getRange(2 + i, 36).setValue('EMAIL_SENT');
  }
});
2021-11-25 23:51:20

Ospravedlňujem sa, budem sa snažiť byť jasnejšie, pri vysvetľovaní problému. Kód je odosielanie e-mailových ako som vyžadovať a "Email_Sent" je umiestnené v stĺpci AJ ako malo. Problém mám súvisí s funkciou fillInTemplateFromObject(tmpl, grg) funkciu. Rozsah ja používam pre túto funkciu je " const grg = list.getRange(2, 1, 5, 36); ' To začína rad 2 rady a zahŕňa 5 riadkov. Keď som odoslanie e-mailu bunky údaje v rozsahu pre šablónu údaje z riadku 6 aj keď riadok, ktorý Email_Sent je v riadku 4. Šablóna by mala prijať dáta z rovnakých buniek, ktoré e-mail sa posiela.
Les

Neviem, ako povedať fillInTemplatefromObject funkciu, vyberte bunky z rovnakého riadku, ktorý sa odošle e-mail. Dúfam, že pochopíte, čo som hľadal dosiahnuť. Vďaka za vašu pomoc.
Les

@Les Ďakujem za odpoveď. Ospravedlňujem sa za moju zlú angličtinu, zručnosť. Z vašej odpovede, som pridal ešte jeden úprava bod v mojej odpovedi. Mohli by ste, prosím, potvrďte ho? Ak som zle vašu otázku znova, ospravedlňujem sa znova.
Tanaike

Áno, je vynikajúce, že to funguje perfektne. Veľmi pekne ďakujem Tanaike
Les

V iných jazykoch

Táto stránka je v iných jazykoch

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................