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.