I am using a Google Script to send an email and look for any responses to it (there should only be one response, but that is not really relevant here). In theory, I can use search, label, and the ReplyTo:
option in GmailApp.sendEmail
to keep track of things. However, I am running into a couple of overlapping issues/concerns because:
- I am sending the same email every week, so search is finicky
- Scripts/Gmail doesn't seem to update quickly enough to find the email it just sent
I want to use the unique Id that Gmail gives every email, but since the GmailApp.sendEmail
method returns a GmailApp
object rather than a GmailMessage
object this doesn't seem possible.
So, how do I programmatically track an email that I have programattically sent?
Below is the code I am using. Open to changes in workflow and methodology, but would prefer to keep this in Google Apps Script.
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);
};
};
Try making a draft, then sending it.
For the issue of search Gmail, have available the following Gmail search operators, operators
after:
before:
can help you.To get the ID of the email sent, I do not know how to get it easily. A proof of concept that comes to mind and that you can adapt and test, is something like:
Besides making all necessary validations (e.g. set a timeout to avoid an infinite loop), will have to check that this does not give problems, e.g.
Script invoked too many times for this user per second
or the like.Another option may be to set another trigger to find the ID of the mail sent. These are just some ideas.