我正在使用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);
};
};