Created
September 24, 2017 03:53
-
-
Save summatix/3d5f0aa995bbdc2e99a3619bf96ef1b4 to your computer and use it in GitHub Desktop.
Autoresponder for gmail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Auto-replies to all messages marked with a certain label. | |
*/ | |
function RespondEmail(e) { | |
// All messages marked with this label will be auto-replied to | |
var autorespondLabel = "autorespond"; | |
// The message content is pulled from a saved draft email. draftSubject | |
// specifies the subject to search for. | |
var draftSubject = "Autorespond"; | |
// The name to reply as | |
var replyFrom = '"My Name" <[email protected]>'; | |
/** | |
* Loads the message from the saved draft with the specified subject. | |
* | |
* @param {string} - The subject of the draft to retrieve the message from. | |
* @return {string} - The message content of the loaded draft. | |
*/ | |
var getDraftMessage = (function(draftSubject) { | |
var message = ""; | |
// Cache the message so we only have to search for the draft once | |
return function(draftSubject) { | |
if (!message) { | |
// Loop through all saved drafts | |
var drafts = GmailApp.getDrafts(); | |
for (var i = 0; i < drafts.length; ++i) { | |
var draft = GmailApp.getDraft(drafts[i].getId()); | |
// End search if we've found the subject we're looking for | |
if (draft.getMessage().getSubject() == draftSubject) { | |
message = draft.getMessage().getBody(); | |
break; | |
} | |
} | |
if (!message) { | |
throw 'Cannot find draft with subject "' + draftSubject + '"'; | |
} | |
} | |
return message; | |
}; | |
}()); | |
// Search for all messages marked with our label | |
var autorespond = GmailApp.getUserLabelByName(autorespondLabel); | |
var messages = GmailApp.search("label:" + autorespondLabel); | |
// Autorespond to all the messages we found. Make sure to remove the | |
// autorespond label so the messages aren't picked up next time. | |
for (var i = 0; i < messages.length; ++i) { | |
var responsebody = getDraftMessage(draftSubject); | |
messages[i].removeLabel(autorespond).reply("", { | |
htmlBody: responsebody, | |
from: replyFrom | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment