1

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).');
  }
}
}
Stefani13
  • 21
  • 1
  • `sendEmail` is only within the scope of `myTriggerFunction`. I'm not sure if you have 2 triggers, `sendEmail` created by `monthlyEmailTrigger` and `myTriggerFunction`. I believe what you want is to create 1 trigger. Replace `ScriptApp.newTrigger('sendEmail')` with `ScriptApp.newTrigger('myTriggerFunction')`. – TheWizEd Apr 15 '22 at 15:18

1 Answers1

0

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.

Daniel
  • 3,157
  • 2
  • 7
  • 15