Gmail脚本在收到的新邮件上运行

时间:2015-07-24 15:27:26

标签: google-apps-script

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

他们是一个谷歌脚本api对收到的邮件采取行动。(onRecieve)?或者我正在考虑添加自定义标签和一些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");
 }

}

更新的脚本:仅供参考,工作得体,但需要更新和清理。

/** 
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
     }
   }
 }

1 个答案:

答案 0 :(得分:1)

你拥有的是一个良好的开端。为了不转发重复项,你可以使用标签,但在这种情况下它可能过度。

而是记住(在脚本属性服务中)上次转发的电子邮件的时间戳。然后使用搜索仅在“之后”查找电子邮件。

如果您在发送电子邮件后保存该属性,您将永远不会错过任何电子邮件,但如果sendmail呼叫在发送后立即崩溃,则可能很少发送重复。 如果您在邮件之前保存该属性,则保证没有重复,但如果在发送电子邮件之前崩溃,可能会遗漏一些。

查看docs和其他s.o.关于如何在“之后:日期”进行搜索的问题。我已经为日期而不是日期时间做了这个。如果仅支持日期,则可能需要跳过某些结果或找到更有效的搜索方式。

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