Reputation: 39
Gmail has the option to schedule mailings from the application.
Is this option implemented in GmailApp.sendEmail()
?
I don't want to use Google Apps Script triggers, I want to use the option given by the GmailApp
Upvotes: 0
Views: 413
Reputation: 10345
Is this option implemented in GmailApp.sendEmail()?
ATTOW, no, please see the official documentation
Bonus: can I schedule this using Gmail API?
ATTOW, also no, see the documentation
Workaround
I understand that you don't want to use triggers, but until the feature is implemented, you can emulate scheduling logic using a trigger and PropertiesService
(or a database of your choosing if you need to store larger emails). Here is a working sample of how you may achieve this (I opted to use a 1 minute trigger, but in real world it might be more pragmatic to use a higher delay between checks):
const sendScheduledEmail = () => {
const propertyName = "emailSchedule";
const store = PropertiesService.getUserProperties();
const savedSchedule = store.getProperty(propertyName) || "[]";
/** @type {emailConfig[]} */
const parsed = JSON.parse(savedSchedule);
if(!parsed.length) {
console.log("Nothing to send");
return;
}
const currentDT = Date.now();
const leftToSend = parsed.filter(emailConfig => {
const {
delay,
subject,
recipient,
body,
options
} = emailConfig;
if (currentDT > delay) {
GmailApp.sendEmail(recipient, subject, body, options);
return false;
}
return true;
});
store.setProperty(propertyName, JSON.stringify(leftToSend));
};
/**
* @typedef {object} delayedConfig
* @property {number} delay
*
* @typedef {object} commonEmailConfig
* @property {string} body
* @property {string} recipient
* @property {string} subject
* @property {GoogleAppsScript.Gmail.GmailAdvancedOptions} options
*
* @typedef {commonEmailConfig & delayedConfig} emailConfig
*
* @param {...emailConfig} configs
* @returns {boolean}
*/
const scheduleEmailSend = (...configs) => {
try {
const now = Date.now();
const normalizedDelayConfigs = configs.map(config => {
const { delay } = config;
config.delay = now + delay;
return config;
});
const checkTriggerName = "sendScheduledEmail", propertyName = "emailSchedule";
const triggers = ScriptApp.getProjectTriggers();
const [trigger] = triggers.filter(trig => trig.getHandlerFunction() === checkTriggerName);
!trigger && ScriptApp.newTrigger(checkTriggerName).timeBased().everyMinutes(1).create();
const store = PropertiesService.getUserProperties();
const savedSchedule = store.getProperty(propertyName) || "[]";
/** @type {emailConfig[]} */
const parsed = JSON.parse(savedSchedule);
parsed.push(...normalizedDelayConfigs);
store.setProperty(propertyName, JSON.stringify(parsed));
} catch (error) {
console.warn(error);
return false;
}
return true;
};
Google is already aware of the feature, please join others on the already opened request - it will have a better chance of being introduced.
Upvotes: 2