Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 21 additions & 17 deletions gmail-sentiment-analysis/Gmail.gs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,18 @@ function analyzeSentiment() {

/**
* Analyzes the sentiment of recent emails in the inbox and labels threads with
* negative sentiment as "UPSET TONE 😡".
* the appropriate sentiment label.
*/
function analyzeAndLabelEmailSentiment() {
const labelName = "UPSET TONE 😡";
const positiveLabelName = "HAPPY TONE 😊";
const neutralLabelName = "NEUTRAL TONE 😐";
const negativeLabelName = "UPSET TONE 😡";
const maxThreads = 10;

// Get the label, or create it if it doesn't exist.
const label = GmailApp.getUserLabelByName(labelName) || GmailApp.createLabel(labelName);
const positiveLabel = GmailApp.getUserLabelByName(positiveLabelName) || GmailApp.createLabel(positiveLabelName);
const neutralLabel = GmailApp.getUserLabelByName(neutralLabelName) || GmailApp.createLabel(neutralLabelName);
const negativeLabel = GmailApp.getUserLabelByName(negativeLabelName) || GmailApp.createLabel(negativeLabelName);

// Get the first 'maxThreads' threads from the inbox.
const threads = GmailApp.getInboxThreads(0, maxThreads);
Expand All @@ -45,25 +49,25 @@ function analyzeAndLabelEmailSentiment() {
// Process each message within the thread.
for (const message of messages) {
const emailText = message.getPlainBody();
const isUpset = isNegativeSentiment(emailText);

if (isUpset) {
thread.addLabel(label);
const sentiment = processSentiment(emailText);

switch (sentiment) {
case 'positive':
thread.addLabel(positiveLabel);
break;
case 'neutral':
thread.addLabel(neutralLabel);
break;
case 'negative':
thread.addLabel(negativeLabel);
break;
default:
break;
}
}
}
}

/**
* Determines if the given text has a negative sentiment.
*
* @param {string} text - The text to analyze.
* @returns {boolean} True if the sentiment is negative, false otherwise.
*/
function isNegativeSentiment(text) {
return processSentiment(text) === 'negative';
}

/**
* Create sample emails
*/
Expand Down
Loading