简体   繁体   中英

How do I set up an apps script trigger to email a Google form at the end of every month?

I created the following Apps Script to automatically email a Google form at the end of every month. I'm getting the error "Script function not found: sendEmail" and I don't know enough about any of this to figure out how to fix it and my googling has been fruitless. Any help is appreciated!!

function monthlyEmailTrigger() {

  ScriptApp.newTrigger('sendEmail')
      .timeBased()
      .atHour(8)
      .everyDays(1)
      .create();
}

function myTriggerFunction()
{
  var today = new Date();
  var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

  if(today.getDate() == lastDayOfMonth.getDate() )
  {
    function sendEmail() {
    GmailApp.sendEmail('myemail@gmail.com', 'Monthly Form',  'Please complete this form (form URL here).');
  }
}
}

The ClockTriggerBuilder Class already has onMonthDay() to run every x day of the month, so you have a few other approaches.

If you don't mind sending the email on the first day of every month you can just set onMonthDay(1)

function monthlyEmailTrigger() {

  ScriptApp.newTrigger('sendEmail')
      .timeBased()
      .onMonthDay(1)
      .create();
}

function sendEmail() {
    GmailApp.sendEmail('myemail@gmail.com', 'Monthly Form',  'Please complete this form (form URL here).');
}

If you really need to run it on the last day, onMonthDay takes values up to 31, but I didn't find any documentation that would confirm whether or not this would work on months with fewer days, so just to be safe you can also create a trigger that runs on the first day of the month, to calculate the last day and set a trigger for that day.

function triggerCreator(){ // run once to create the trigger
  ScriptApp.newTrigger('monthlyTrigger')
      .timeBased()
      .onMonthDay(1) //the trigger will runs every 1st day of the month
      .create()
}

function monthlyTrigger(){
  let today = new Date()
  let month = today.getMonth()+1
  let year = today.getFullYear()

  let lastday = daysInMonth(today.getMonth()+1, year) // calculates last day of the current month
  
  ScriptApp.newTrigger('sendEmail')
      .timeBased()
      .atDate(year, month, lastday) //sets the trigger to run the last day of the current month
      .create()
}

function daysInMonth (month, year) {
  return new Date(year, month, 0).getDate();
}

function sendEmail() {
  GmailApp.sendEmail('myemail@gmail.com', 'Monthly Form',  'Please complete this form (form URL here).');
}

Credit to this answer for the daysInMonth() function.

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