Google apps script 在收到新邮件时运行Gmail脚本

Google apps script 在收到新邮件时运行Gmail脚本,google-apps-script,Google Apps Script,我正试图写一个脚本,将邮件从我的工作gmail转发到个人电子邮件。脚本只需要从周一到周五,下午4点到早上7点之间运行。我陷入困境的地方是在这段时间内每5分钟运行一次脚本,并且只转发新邮件 他们是否有谷歌脚本api来对收到的邮件执行操作(OnReceive)?或者我正在考虑添加一个自定义标签和一些if语句,以确保不转发重复的内容 下面是我现在要讲的泛型 function startCustomTrigger() { ScriptApp.newTrigger('nonWorkHours').ti

我正试图写一个脚本,将邮件从我的工作gmail转发到个人电子邮件。脚本只需要从周一到周五,下午4点到早上7点之间运行。我陷入困境的地方是在这段时间内每5分钟运行一次脚本,并且只转发新邮件

他们是否有谷歌脚本api来对收到的邮件执行操作(OnReceive)?或者我正在考虑添加一个自定义标签和一些if语句,以确保不转发重复的内容

下面是我现在要讲的泛型

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("example@example.com");
 }

}
函数startCustomTrigger()
{
ScriptApp.newTrigger('nonWorkHours').timeBased().everyMinutes(5.create();
}
函数非工作时间(){
变量日期=新日期();
var day=date.getDay();
var hrs=date.getHours();
如果((天>=1)和(&(天=16)和(&)(小时)与以下记录行合并
Logger.log(“开始运行:“+Utilities.formatDate(新日期(startTime),Session.getScriptTimeZone(),'d MMM yy hh:mm:ss”);//将时间记录为可读格式
//抓取gmail收件箱
var thread=GmailApp.search('is:unread');//抓取所有未读消息
var gmailMessages=GmailApp.getMessagesForThreads(thread);//获取上面设置的给定线程的所有消息
//设置脚本时间戳属性
var lastForwardTime=scriptProperties.getProperties();//上次运行scirpt时最后一条消息的时间戳的var
var keys=scriptProperties.getProperty('lastForward');//来自lastForward时间戳的键
log(“转发消息的最后时间戳:“+keys)//将密钥记录到记录器
Logger.log(“label:+GmailApp.createLabel(“转发(非小时)”);//创建标签,如果存在,将覆盖
//变量,用于将标签“转发(非小时)”设置为正在转发的线程
var label=GmailApp.getUserLabelByName(“转发(非小时)”;
//设置一些时间格式,检查M-F和下午4点到上午7点之间
变量日期=新日期();
var day=date.getDay();
Logger.log(天);
var hrs=date.getHours();
Logger.log(小时);
//=========================================================================================================================

如果(hrs>=16&&hrs=1&&hrs=1)&(day=6)&(day你有一个好的开始。为了不转发重复项,你可以使用标签,但在这种情况下,它是多余的

相反,请记住(在脚本属性服务中)转发的最后一封电子邮件的时间戳。然后使用搜索仅查找“之后”的电子邮件

如果在发送电子邮件后保存该属性,您将永远不会错过电子邮件,但如果sendmail呼叫在发送后立即崩溃,则很少会发送重复的电子邮件。 如果您在发送邮件之前保存了所有权,则可以保证没有重复项,但如果在发送电子邮件之前崩溃,则可能会丢失一些

查看文档和其他s.o.问题,了解如何在“日期之后”进行搜索。我已经对日期进行了搜索,但没有对日期时间进行搜索。如果只支持日期,您可能需要跳过一些结果或找到更有效的搜索方法


在电子邮件序列没有模式的一般情况下,使用标签是好的。在您的情况下,新收件箱邮件总是连续的。

不幸的是,没有onReceive触发器。您是否考虑过检查接收时间是否在过去5分钟内?
/** 
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("tjones@livefake.com");  //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
     }
   }
 }