I have a script that, when I run it, will automatically respond to emails with the subject "For Review (TEST):" with an automated message. Basically, if the subject of the email contains a specific date, the script will look to see if there is a Bank Holiday within the last 7 days and if so, it will be included in the auto-response.
Right now, I have this on a timer to run every hour, but the ideal version of this is that it would run each time I get an email with the subject "For Review (TEST):". However, this doesn't seem to be an option when I go to set up the Trigger. Is this something Google does not allow?
EDIT: I have pieced together the following script and have configured my GCC with the information below. This is my first GCC project and I am still wrapping my head around how it works. I have sent my self a test email, but nothing has happened. Do I have this configured correctly? From the handleEmailNotification function below, I should get an email anytime my inbox gets an email with the subject line "For Review (TEST):"
MY SCRIPT
function setupGmailWatch() {
const topicName = 'projects/PROJECTID/topics/TOPIC';
const url = 'https://www.googleapis.com/gmail/v1/users/me/watch';
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/json',
muteHttpExceptions: true,
payload: JSON.stringify({
labelIds: ['INBOX'],
topicName: topicName
})
};
const response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
};
function createWatchTrigger() {
try {
ScriptApp.newTrigger('setupGmailWatch')
.timeBased()
.everyWeeks(1)
.create();
} catch (e) {
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Failed to set up Gmail Watch trigger',
body: 'An error occurred when trying to set up the Gmail Watch trigger: ' + e.message
});
}
};
function handleEmailNotification(message) {
const data = Utilities.newBlob(Utilities.base64DecodeWebSafe(message.data)).getDataAsString();
const emailData = JSON.parse(data);
const historyId = emailData.historyId;
const historyList = Gmail.Users.History.list('me', {startHistoryId: historyId, historyTypes: 'messageAdded'});
const messages = historyList.history.map(function(history) {return history.messages;}).flat();
messages.forEach(function(message) {
const email = GmailApp.getMessageById(message.id);
const subject = email.getSubject();
// Check if the email subject is "For Review (TEST):"
if (subject.includes("For Review (TEST):")) {
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'YOU GOT AN EMAIL',
body: 'You got an email'
});
}
});
};
function doPost(e) {
var message = JSON.parse(e.postData.contents).message;
handleEmailNotification(message);
return ContentService.createTextOutput();
};
I made a sample of the process, it is a little tricky, since you need to make sure you follow all the steps correctly. If one of them is missing, you will get an error message.
Here are the steps:
You will need to create a project.
Setup and OAuth consent screen
. Steps can be found here.
Link the GCP project to your Apps script project. (if you do not have one, you will need to create it following the steps here).
Enable the pub/sub API in the project linked to the Apps script.
Create a Topic
& Subscription
as pull
(i.e. initiated by your app) in the GCP project. You can do this by following the steps here, or you can click on Guide me
in the same documentation for step-by-step guidance.
Add gmail-api-push@system.gserviceaccount.com
as a principal
, you can do this in the IAM
page or inside the topic
page.
Go back to the Apps Script project, and enable Show "appsscript.json" manifest file in editor
from the Project settings
.
Add the following scopes to the manifest.
"oauthScopes": [
"https://mail.google.com/",
"https://www.googleapis.com/auth/pubsub",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/gmail.metadata",
"https://www.googleapis.com/auth/script.external_request"
]
Add the Gmail API
advance services to the Apps Script project.
I personally created a filter in the Gmail settings
to automatically sort all the emails with a specific subject to a label called PubSub
.
Lastly, here is a sample code for Pub/Sub
using labels.
function testWebhooks() {
let email = 'user@domain.com';
let data = request_body = {
"labelIds": [
'PubSub'
],
"labelFilterBehavior": 'INCLUDE',
"topicName": 'projects/project-111/topics/the_topic'
};
let watchResponse = Gmail.Users.watch(data,email)
console.log(watchResponse);
}
Note: All the hyperlinks will take you to the Google Documentation you need to follow to complete the steps and you can also us this article
As per Google Documentation:
Additionally, a successful watch call should cause a notification to immediately be sent to your Cloud Pub/Sub topic.
You will see the history inside of
If you want to receiving notifications inside the subscription that you created. Inside Pub/Sub
> Subscriptions
> Select the subscription you created
> Messages
tab > Pull
.
If you want to receive email notification to your inbox, when your pub/sub subscription receives a message, then you will need to add a Pub/Sub trigger, you can use a cloud function
for it. You can read more about it in this documentation, or you can use `background functions` more information here.