Я пытаюсь написать сценарий, который пересылает почту из моей работы gmail в личный адрес электронной почты. Сценарий должен запускаться только с Пн-Пт, с 16:00 до 7:00. Место, где я застреваю, - это возможность запускать скрипт каждые 5 минут за это время и перенаправлять только новую почту.Скрипт Gmail запускается при получении новой почты
Это их скрипт google для совершения действия на полученной почте. (OnRecieve)? Или я смотрю на добавление пользовательской метки и некоторых операторов if, чтобы я не пересылал дубликаты.
Heres the generics того, что я сейчас иду.
function startCustomTrigger()
{
ScriptApp.newTrigger('nonWorkHours').timeBased().everyMinutes(5).create();
}
function nonWorkHours() {
var date = new Date();
var day = date.getDay();
var hrs = date.getHours();
if ((day >= 1) && (day <= 5) && (hrs >= 16) && (hrs <= 7)) {
// forward email here
var thread = GmailApp.getInboxThreads(0,1)[0]; // get first thread in inbox
var message = thread.getMessages()[0]; // get first message
message.forward("[email protected]");
}
}
Обновленный скрипт: FYI, работает достойно, но нуждается в обновлении и очистке.
/**
Forward unread inbox messages to personal email at desired hours. M - F from 4pm to 7am and Sat all day.
Also mark the messages that are forwarded with custom label "Forwarded(Non_Hours)" and marked as read.
Grab timestamp of last message that was forwarded and save as global script property.
tjones © 2015
TimeMailed
**/
// Custom trigger to run script every 5 mins
function startCustomTrigger()
{
ScriptApp.newTrigger('timeBound').timeBased().everyMinutes(5).create()
}
// Global Variables ====================================================================================================
var scriptProperties = PropertiesService.getScriptProperties();
//Grab current time of run
var startTime = new Date().getTime(); //Log the start of script--> combine with below Logger line
Logger.log("START OF RUN: " + Utilities.formatDate(new Date(startTime),Session.getScriptTimeZone(),'d MMM yy hh:mm:ss')); //Log time into readable format
// Grab gmail inbox
var thread = GmailApp.search('is:unread'); //Grab all unread messages
var gmailMessages = GmailApp.getMessagesForThreads(thread); //Grab all the messages of given threads, set above
//Setup script timestamp properties
var lastForwardTime = scriptProperties.getProperties(); //Var for the timestamp of last message from last time scirpt ran
var keys = scriptProperties.getProperty('lastForward'); //The key from the lastForward timestamp
Logger.log("LAST TIMESTAMP OF MESSAGE FORWARDED: " + keys) //Log the key to the logger
Logger.log("label: " + GmailApp.createLabel("Forwarded(Non_Hours)")); //Create label, if exists will just overwrite
//Variable to set label "Forwarded(Non_Hours)" to threads being forwarded
var label = GmailApp.getUserLabelByName("Forwarded(Non_Hours)");
//Set some time formats to check if between M-F and 4pm to 7am
var date = new Date();
var day = date.getDay();
Logger.log(day);
var hrs = date.getHours();
Logger.log(hrs);
//=========================================================================================================================
if (hrs >= 16 && hrs <= 24) {
var inBound = true;
} else if (hrs >= 1 && hrs <= 6) {
inBound = true;
} else {
inBound = false;
}
function timeBound() {
if ((day >= 1) && (day <= 5) && (inBound == true)) {
timeMailed();
}
else if ((day >=6) && (day <=7)) {
timeMailed();
}
else {
Logger.log("Time is out of bounds, Within work hours: Sleeping for 5 mins");
}
}
// Meat and potatoes of forwarding
function timeMailed() {
for(var i=0;i<thread.length;i++){ //for loop for all the threads from above
var messagesForThread = gmailMessages[i]; //var for messages in threads
label.addToThread(thread[i]) // Set label to thread
GmailApp.markThreadRead(thread[i]); //Mark messages as read before forwarding them
for(var j=0;j<messagesForThread.length;j++){ //for loop to go through messages found above
// Get timestamps of messages for duplicate check
var messageDateTime = messagesForThread[j].getDate();
Logger.log(messagesForThread[j].getDate());
var messageEpocTime = messageDateTime.getTime();
Logger.log(messageDateTime.getTime());
// Compare message timestamp to lastForward key and make sure its newer than last check
if (messageEpocTime > scriptProperties.getProperty('lastForward')) {
scriptProperties.setProperty('lastForward', messageEpocTime); //Get date of messages and set as script property "lastForward"
messagesForThread[j].forward("[email protected]"); //forward the messages from above to forward address
Logger.log("Message with subject " + messagesForThread[j].getSubject() + " was forwarded")
}
else {
Logger.log("Message with subject " + messagesForThread[j].getSubject() + " was already forwarded within last 5 min check")
}
Logger.log("FINAL TIMESTAMP AT: " + scriptProperties.getProperty('lastForward')); //Leave in final run to log last timestamp
}
}
}
К сожалению, нет встроенного триггера onReceive. Рассматривали ли вы проверку времени приема за последние 5 минут? –