Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Automatically sends Gmail drafts with specific label.
/*
* Inspired by: http://stackoverflow.com/a/27215474
*
* After copying the code to your own script, open Resources -> Advanced Google Services,
* 1. enable Gmail API (switch to "on"),
* 2. open the link for the Google Developers Console, and enable the Gmail API for your project.
*/
function sendMorningDrafts() {
sendLabeledDrafts("schedule/send-next-0700-0800");
}
function sendEveningDrafts() {
sendLabeledDrafts("schedule/send-next-1800-1900");
}
function sendLabeledDrafts(label_to_send){
var drafts = Gmail.Users.Drafts.list('me')["drafts"];
if (!drafts) { return; } // No draft exists.
for (var i=0; i<drafts.length; i++) {
var draft_id = drafts[i]["id"];
// var message = GmailApp.getMessageById(drafts[i]["message"]["id"]); // You can get message id too, but not necessary in this script.
var thread = GmailApp.getThreadById(drafts[i]["message"]["threadId"]);
var sent_flag = false;
var labels = thread.getLabels();
for (var j=0; j<labels.length; j++) {
var label = labels[j];
if (label.getName() === label_to_send) {
var response = Gmail.Users.Drafts.send({"id": draft_id}, "me");
var sent_flag = true;
var new_thread = GmailApp.getThreadById(response["threadId"]);
// Removing label (to avoid future missending).
var sent_labels = new_thread.getLabels();
for (var k=0; k<sent_labels.length; k++){
var sent_label = sent_labels[k];
if (sent_label.getName() === label_to_send) {
new_thread.removeLabel(sent_label);
}
}
}
if (sent_flag) { break; }
}
if (sent_flag) { continue; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment