简体   繁体   中英

How to automate Google Sheet Email to send within quota and daily?

I have the following Google Script to send emails via Google Sheets. But I don't want to send beyond the quota.

Instead I want to send within quota (I think its 50 emails at a time) and the next 50 recipients the next day until end of email list.

How do I do that?

function sendEmail() {var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Sheet1');
var sheet2=ss.getSheetByName('Sheet2');
var subject = sheet2.getRange(2,1).getValue();
var message = sheet2.getRange(2,2).getValue();
var n=sheet1.getLastRow();
for (var i = 2; i < n+1 ; i++ ) {
var emailAddress = sheet1.getRange(i,3).getValue();
MailApp.sendEmail(emailAddress, subject, message);
}

}

Solution:

First you would need the script to send only 50 emails per execution. This script would send to the first 50 addresses on the list in Sheet1 and move them to Sheet3 , so there is no need to change anything in the code:

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName('Sheet1');
  var sheet2 = ss.getSheetByName('Sheet2');
  var sheet3 = ss.getSheetByName('Sheet3');
  var subject = sheet2.getRange(2,1).getValue();
  var message = sheet2.getRange(2,2).getValue();

  var lr1 = sheet1.getLastRow() > 50 ? 50 : sheet1.getLastRow() - 1;
  console.log(lr1);
  var emailAddresses = sheet1.getRange(2,3,lr1).getValues();
  
  var lr3 = sheet3.getLastRow();
  var doneAddresses = sheet3.getRange(lr3+1,3,lr1);

  for (var i=0; i < lr1; i++) {
    MailApp.sendEmail(emailAddresses[i][0], subject, message);
  }

  doneAddresses.setValues(emailAddresses);
  sheet1.deleteRows(2,lr1);
}

Then you need to create an installable time-based trigger that runs every 24 hours, or you can also configure it at a specified time:

function createTimeDrivenTriggers() {
  ScriptApp.newTrigger('sendEmail')
      .timeBased()
      .everyHours(24) // or change this to .atHour(8) to run every 8AM
      .create();
}

Run this function only once to create this installable trigger. sendEmail() will then run daily. Please take note of the restrictions in the documentation.

Sample Data:

I used a sample sheet with 80 dummy addresses and ran the script once. Of course the email will fail, but the other parts of the script work as expected.

Sheet1

在此处输入图像描述

Sheet3

在此处输入图像描述

References:

Installable Triggers

Clock Trigger Builder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM