Wysyłam e-maile za pomocą Google arkuszy przy użyciu szablonu

0

Pytanie

Próbuję uruchomić skrypt poniżej, wysyłając e-maile z szablonu na kartce[1] A1. Za każdym razem, gdy skrypt uruchomi się, że wybiera dane dla funkcji fillInTheTemplate z zakresu

const grg = sheet.getRange(2, 1, 6, 36); Żądam, aby kod wybierać zakres tylko dla funkcji fillTemplateFunction z wiersza, w którym nie ma "Email_Sent" w wierszu 36

Dziękuję za wszelką 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

Najlepsza odpowiedź

1

Kiedy zobaczyłem twój skrypt, wydawało mi się, że twój skrypt wysyła wiadomość e-mail, sprawdzając w kolumnie "K" (numer kolumny 11) i kolumnę "AJ" (numer kolumny 36) z if (status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT') {}. I kiedy zobaczyłem twój wzór arkusza, numer wiersza, w którym nie ma wartości "EMAIL_SENT" w kolumnach "AJ", jest równa 5. Ale, gdy zobaczyłem nagłówek "K", żadnego znaczenia nie ma. Tym samym, status == 'PRICE ONLY' && emailSent != 'EMAIL_SENT' ZWROT false. W tym wiadomości e-mail nie jest wysyłana. Pomyślałem, że to może być przyczyną twojego problemu.

Jeśli chcesz wysłać wiadomość e-mail, gdy w kolumnie "AJ" nie ma znaczenia "EMAIL_SENT", jak o kolejnej zmiany?

Od:

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

Dla:

if (emailSent != 'EMAIL_SENT') {

Dodano:

Z nowej odpowiedzi,

Kod wysyła wiadomość e-mail, jak wymagam, i "Email_Sent" mieści się w kolumnę AJ, jak być powinno. Problem, z którym mam do czynienia, jest związana z funkcją fillInTemplateFromObject(tmpl, grg). Zakres, który używam tej funkcji jest równy 'const grg = sheet.getRange(2, 1, 5, 36);' To zaczyna się od wiersza 2 wierszy i składa się z 5 wierszy. Gdy wysyłam wiadomość e-mail, dane komórki w zakresie danych szablonu znajdują się w wierszu 6, nawet jeśli wiersz, w którym znajduje się adres e-mail, jest ciągiem 4. Szablon powinien pobierać dane z tych samych komórek, z których wysyłany jest e-mail.

W tym przypadku, jak o kolejnej modyfikacji?

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');
    }
  });

Dla:

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

Przepraszam, postaram się być bardziej jasne w wyjaśnieniu problemu. Kod wysyła wiadomość e-mail, jak wymagam, i "Email_Sent" mieści się w kolumnę AJ, jak być powinno. Problem, z którym mam do czynienia, jest związana z funkcją fillInTemplateFromObject(tmpl, grg). Zakres, który używam tej funkcji jest równy 'const grg = sheet.getRange(2, 1, 5, 36);' To zaczyna się od wiersza 2 wierszy i składa się z 5 wierszy. Gdy wysyłam wiadomość e-mail, dane komórki w zakresie danych szablonu znajdują się w wierszu 6, nawet jeśli wiersz, w którym znajduje się adres e-mail, jest ciągiem 4. Szablon powinien pobierać dane z tych samych komórek, z których wysyłany jest e-mail.
Les

Nie wiem, jak określić funkcje fillInTemplatefromObject, żeby wybierała komórki z tego samego wiersza, z którego jest wysyłana wiadomość e-mail. Mam nadzieję, że zrozumiesz, co chcę osiągnąć. Dziękuję za pomoc.
Les

@Les Dziękuję, że odpowiedzieliście. Przepraszam za moja słaba znajomość języka angielskiego. Z twojej odpowiedzi, dodałem swoją odpowiedź jeszcze jedna zmiana. Nie mógłbyś, proszę to potwierdzić? Jeśli znowu źle zrozumiałem twoje pytanie, jeszcze raz przepraszam.
Tanaike

Tak, dobrze, to świetnie działa. Bardzo dziękuję Танайке
Les

W innych językach

Ta strona jest w innych językach

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