2013-08-27 140 views
3

我正在使用Google脚本来发送电子邮件并查找对其的任何响应(应该只有一个响应,但这不是真正相关的)。理论上,我可以使用搜索,标签和GmailApp.sendEmail中的ReplyTo:选项来跟踪事情。但是,我遇到了几个重叠的问题/顾虑,因为:在Google Apps脚本中访问已发送的电子邮件

  • 我每星期发送相同的电子邮件,所以搜索是挑剔
  • 脚本/ Gmail看起来似乎没有足够快地找到更新电子邮件只是发送

我想使用的唯一ID Gmail提供的每封电子邮件,但自从GmailApp.sendEmail方法返回一个GmailApp对象,而不是一个GmailMessage对象这似乎并不可能。

那么,如何以编程方式跟踪我已编程发送的电子邮件?

以下是我正在使用的代码。开放以改变工作流程和方法,但希望将其保留在Google Apps脚本中。

function trigger(minutes){ 
ScriptApp.newTrigger("checkForEmail") 
.timeBased() 
.after(100*60*minutes) 
.create() 
}; 

function sendEmail(){ 
//send the email 
    GmailApp.sendEmail("[email protected]","Subject","Body",{replyTo: "[email protected]"}); 
    //get the Id of the email that was just sent 
    var emailId GmailApp.search("replyTo:[email protected]",0,1)[0].getMessages()[0]; 
    ScriptProperties.setProperty("emailId", emailId); 
    //set a trigger to check later 
    trigger(45) 
    }; 

function checkForEmail(){ 
var emailId = ScriptProperties.getProperty("emailId"); 
var email = GmailApp.getMessageById(emailId); 
var count = email.getThread().getMessageCount(); 
var command = "checkForEmail" 
if (count == 1){ 
//set trigger to check again 
ScriptApp.deleteTrigger(command) 
trigger(5) 
} 
if (count == 2){ 
//do stuff with the new email: alert me, download attachments, etc. 
var attachments = email.getThread().getAttachments() 
ScriptApp.deleteTrigger(command); 
} 
else { 
//something is weird, let me know 
var body = "there was an error with checking an email ("+emailId+")." 
GmailApp.sendEmail("[email protected]","Error",body); 
ScriptApp.deleteTrigger(command); 
}; 
}; 

回答

1

对于搜索Gmail中的问题,提供以下Gmail search运营商,运营商after:before:可以帮助你。

要获取发送的电子邮件的ID,我不知道如何轻松获取。我想到的,并且可以适应和测试概念的证明,是这样的:

... 
    GmailApp.sendEmail("[email protected]","Subject","Body",{replyTo: "[email protected]"}); 
    do { 
    /* The search should be as accurate as you can */ 
    threads = GmailApp.search('replyTo:[email protected] is:sent before:2013/08/27 after:2013/08/27 subject:"Subject"', 0, 1); 
    } while(!threads.length); 
    ... 

除了使所有必要的验证(如设置超时时间以避免无限循环),则要检查这不会给出问题,例如Script invoked too many times for this user per second等。

另一个选项可能是设置另一个触发器来查找发送邮件的ID。这些只是一些想法。

相关问题