我正在使用Google脚本发送电子邮件并查找对其的任何回复(应该只有一个回复,但这在这里并不重要)。理论上,我可以使用ReplyTo:
中的搜索,标签和GmailApp.sendEmail
选项来跟踪事物。但是,我遇到了几个重叠的问题/担忧,因为:
我想使用Gmail为每封电子邮件提供的唯一ID,但由于GmailApp.sendEmail
方法返回GmailApp
对象而不是GmailMessage
对象,因此这似乎不可行。< / p>
那么,我如何以编程方式跟踪我以编程方式发送的电子邮件?
以下是我正在使用的代码。可以更改工作流程和方法,但更愿意将其保留在Google Apps脚本中。
function trigger(minutes){
ScriptApp.newTrigger("checkForEmail")
.timeBased()
.after(100*60*minutes)
.create()
};
function sendEmail(){
//send the email
GmailApp.sendEmail("name@gmail.com","Subject","Body",{replyTo: "myname+modifier@gmail.com"});
//get the Id of the email that was just sent
var emailId GmailApp.search("replyTo:name+modifier@gmail.com",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("myname@gmail.com","Error",body);
ScriptApp.deleteTrigger(command);
};
};
答案 0 :(得分:2)
尝试制作草稿,然后发送。
var message = GmailApp.createDraft("name@gmail.com","Subject","Body",{replyTo: "myname+modifier@gmail.com"}).send();
答案 1 :(得分:1)
对于搜索Gmail问题,可以使用以下Gmail search运营商,运营商after:
before:
可以为您提供帮助。
要获取已发送电子邮件的ID,我不知道如何轻松获取。想到的概念证明,你可以适应和测试,就像:
...
GmailApp.sendEmail("name@gmail.com","Subject","Body",{replyTo: "myname+modifier@gmail.com"});
do {
/* The search should be as accurate as you can */
threads = GmailApp.search('replyTo:name+modifier@gmail.com 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。这些只是一些想法。