K
K
K-VKO2021-10-27 11:43:21
Google Apps Script
K-VKO, 2021-10-27 11:43:21

Send email from Google Sheets by condition?

There is such a Google spreadsheet that we maintain in our store:
617910e490b5a062317276.jpeg

Is it possible to do something so that when the status of an order changes, a letter is sent to the client with the changes? For example - Hello, the status of your order has been changed to "Sent"

Who will give the working code - I will contact and thank you

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladislav Orlov, 2021-10-27
@haveacess

Did you try to use google?
triggers. OnEdit(e)
For to do something if conditions was passed
--
Sending email
Only working for you google account, of course.
Atetion 1: Triggers can be did very very slow you application. Please be careful when you do it. Or using triggers on schedule.
Atetion 2: Don`t forget about Credentials in Google App Script (just run you script in editor and then follow the instructions)

G
Grigory Boev, 2021-10-28
@ProgrammerForever

Need to use onEdit and MailApp
Demo Table

M
Maxim Stoyanov, 2021-11-01
@stomaks

Here is the working code:

/**
 * Конфигурация.
 */
const CONFIG = {};

// Рабочие листы
CONFIG.sheets = [
  `Журнал заказов`
];

CONFIG.cols = {};

// Порядок столбцов
CONFIG.cols[`Заказ`] = 1;
CONFIG.cols[`Email`] = 2;
CONFIG.cols[`Статус`] = 3;



/**
 * Отправляет письмо при смене статуса.
 * 
 * @param {Object} event
 */
function onEditTrigger(event = {}) {
  try {
    if (!event.source)
      event.source = SpreadsheetApp
        .getActiveSpreadsheet();

    if (!event.range)
      event.range = SpreadsheetApp
        .getActiveRange();

    // Открыть текущий лист
    const sheet = event.source
      .getActiveSheet();

    // Обходим листы не из списка
    if (!CONFIG.sheets.includes(sheet.getName()))
      return;

    // Номер активной строки
    const row = event.range
      .getRow();

    // Обходим закрепленные строки
    if (row <= sheet.getFrozenRows())
      return;

    // Номер активного столбца
    const col = event.range
      .getColumn();

    // Обхотим столбцы (не статус)
    if (col !== CONFIG.cols[`Статус`])
      return;

    // Получаем данные строки
    const values = sheet
      .getRange(`${row}:${row}`)
      .getValues()[0];

    const recipient = values[CONFIG.cols[`Email`] - 1];
    const status = values[CONFIG.cols[`Статус`] - 1];

    const subject = `Заголовок письма`;
    const body = `Здравствуйте, статус вашего заказа изменен на "${status}"`;

    // Отправляем письмо
    const response = MailApp
      .sendEmail(recipient, subject, body);

    if (!response)
      throw new TypeError(`Не удалось отправить письмо!`);

    console.log(`Письмо успешно отправлено!`, recipient, subject, body);
  }
  catch (error) {
    console.error(error.stack);

    throw new Error(error.toString());
  }
};

For this to work, you need to:
1. Open the script editor in the table and paste the code above there.
617ff57ce528c038052771.png
2. Create a new trigger
617ff5559eed5232989193.png
---
Maxim Stoyanov (stomaks), Google Apps Script developer .
g-apps-script.com
stomaks.me

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question