Skip to content

Instantly share code, notes, and snippets.

@likecyber
Last active October 31, 2023 14:08
Show Gist options
  • Save likecyber/e74016f7fc65b92563e8848f0b8a93e4 to your computer and use it in GitHub Desktop.
Save likecyber/e74016f7fc65b92563e8848f0b8a93e4 to your computer and use it in GitHub Desktop.
Forward Gmail to HTTP with Google Apps Script
// Simply run Install function once to setup.
// The following script does send HTTP requests for each unread email from any sender with the email domain '@domain.com'.
// The emails are processed in chronological order, from the oldest to the newest.
// This script is implemented with Single Instance Locking to prevent duplication.
// This script is implemented with Execution Timeout to prevent the execution time limit from being exceeded.
function Install () {
Uninstall();
ScriptApp.newTrigger('Run').timeBased().everyMinutes(1).create();
}
function Uninstall () {
for (const trigger of ScriptApp.getProjectTriggers()) {
if (trigger.getHandlerFunction() === 'Run') {
ScriptApp.deleteTrigger(trigger);
}
}
}
function isInstalled () {
let installed = false;
for (const trigger of ScriptApp.getProjectTriggers()) {
if (trigger.getHandlerFunction() === 'Run') {
installed = true;
break;
}
}
return installed;
}
function Run () {
const startTime = new Date();
const lock = LockService.getScriptLock();
try {
if (lock.tryLock(100)) {
if (!isInstalled()) {
Install();
}
let index = 0;
let threads = [];
let olderThreads = [];
do {
olderThreads = GmailApp.search('is:unread from:(@domain.com)', index += olderThreads.length, 500);
threads = threads.concat(olderThreads).slice(-100);
} while (olderThreads.length === 500);
(() => {
for (const thread of threads.reverse().slice(0, 100)) {
for (const message of thread.getMessages()) {
if (new Date() - startTime < 300000) {
message.refresh();
if (message.isUnread()) {
message.markRead();
if (message.getHeader('Authentication-Results').split(';').map((line) => line.trim().split(' ')[0]).slice(1).every((check) => check.endsWith('=pass'))) {
UrlFetchApp.fetch('https://...', {
method: 'POST',
payload: {
from: message.getFrom(),
subject: message.getSubject(),
body: message.getBody(),
plainBody: message.getPlainBody(),
timestamp: message.getDate().getTime()
}
});
}
}
} else {
return;
}
}
}
})();
}
} finally {
lock.releaseLock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment