Discover Reliable Emails in your Gmail Spam Folder with AI and Google Script

Shubham
10 Min Read

Use AI to enhance spam detection in Gmail and discover respectable emails that have been mistakenly marked as spam by Google algorithms.

False positives in Gmail are unusual however can occur, which means an essential e mail may mistakenly find yourself in your spam folder. While you’re coping with tons of of spam messages day by day, figuring out these respectable emails turns into much more difficult.

You may create filters in Gmail such that emails from particular senders or with sure key phrases are by no means marked as spam. However these filters would clearly not work for emails from new or unknown senders.

Discover incorrectly categorised messages in Gmail Spam

What if we used AI to investigate our spam emails in Gmail and predict which of them are doubtless false positives? With this checklist of misclassified emails, we may mechanically transfer these emails to the inbox or generate a report for guide evaluate.

Right here’s a pattern report generated from Gmail. It features a checklist of emails with a low spam rating which are doubtless respectable and ought to be moved to the inbox. The report additionally features a abstract of the e-mail content material in your most well-liked language.


To get began, open this Google Script and make a replica of it in your Google Drive. Swap to the Apps Script editor and supply your e mail tackle, OpenAI API key, and most well-liked language for the e-mail abstract.

Select the reportFalsePositives operate from the dropdown and click on the play button to run the script. It’ll seek for unread spam emails in your Gmail account, analyze them utilizing OpenAI’s API, and ship you a report of emails with a low spam rating.

If you need to run this script mechanically at common intervals, go to the “Triggers” menu within the Google Apps Script editor and arrange a time-driven set off to run this script as soon as every single day as proven under. You can too select the time of the day while you want to obtain the report.


Google Script - Time Trigger

How AI Spam Classification Works – The Technical Half

If you’re curious to understand how the script works, here’s a temporary overview:

The Gmail Script makes use of the Gmail API to seek for unread spam emails in your Gmail account. It then sends the e-mail content material to OpenAI’s API to categorise the spam rating and generate a abstract in your most well-liked language. Emails with a low spam rating are doubtless false positives and might be moved to the inbox.

1. Person Configuration

You may present your e mail tackle the place the report ought to be despatched, your OpenAI API key, your most well-liked LLM mannequin, and the language for the e-mail abstract.


const USER_EMAIL = 'e mail@area.com'; 
const OPENAI_API_KEY = 'sk-proj-123'; 
const OPENAI_MODEL = 'gpt-4o'; 
const USER_LANGUAGE = 'English'; 

2. Discover Unread Emails in Gmail Spam Folder

We use the epoch time to search out spam emails that arrived within the final 24 hours and are nonetheless unread.

const HOURS_AGO = 24; 
const MAX_THREADS = 25; 

const getSpamThreads_ = () => {
  const epoch = (date) => Math.flooring(date.getTime() / 1000);
  const beforeDate = new Date();
  const afterDate = new Date();
  afterDate.setHours(afterDate.getHours() - HOURS_AGO);
  const searchQuery = `is:unread in:spam after:${epoch(afterDate)} earlier than:${epoch(beforeDate)}`;
  return GmailApp.search(searchQuery, 0, MAX_THREADS);
};

3. Create a Immediate for the OpenAI Mannequin

We create a immediate for the OpenAI mannequin utilizing the e-mail message. The immediate asks the AI mannequin to investigate the e-mail content material and assign a spam rating on a scale from 0 to 10. The response ought to be in JSON format.

const SYSTEM_PROMPT = `You might be an AI e mail classifier. Given the content material of an e mail, analyze it and assign a spam rating on a scale from 0 to 10, the place 0 signifies a respectable e mail and 10 signifies a particular spam e mail. Present a brief abstract of the e-mail in ${USER_LANGUAGE}. Your response ought to be in JSON format.`;

const MAX_BODY_LENGTH = 200; 

const getMessagePrompt_ = (message) => {
  const physique = message
    .getPlainBody()
    .exchange(/https?://[^s>]+/g, '')
    .exchange(/[nrt]/g, ' ')
    .exchange(/s+/g, ' ')
    .trim(); 
  return [
    `Subject: ${message.getSubject()}`,
    `Sender: ${message.getFrom()}`,
    `Body: ${body.substring(0, MAX_BODY_LENGTH)}`,
  ].be part of('n');
};

4. Name the OpenAI API to get the Spam Rating

We cross the message immediate to the OpenAI API and get the spam rating and a abstract of the e-mail content material. The spam rating is used to find out if the e-mail is a false optimistic.

The tokens variable retains monitor of the variety of tokens used within the OpenAI API calls and is included within the e mail report. You should use this data to watch your API utilization.

let tokens = 0;

const getMessageScore_ = (messagePrompt) => {
  const apiUrl = `https://api.openai.com/v1/chat/completions`;
  const headers = {
    'Content material-Kind': 'software/json',
    Authorization: `Bearer ${OPENAI_API_KEY}`,
  };
  const response = UrlFetchApp.fetch(apiUrl, {
    methodology: 'POST',
    headers,
    payload: JSON.stringify({
      mannequin: OPENAI_MODEL,
      messages: [
        { role: 'system', content: SYSTEM_PROMPT },
        { role: 'user', content: messagePrompt },
      ],
      temperature: 0.2,
      max_tokens: 124,
      response_format: { kind: 'json_object' },
    }),
  });
  const information = JSON.parse(response.getContentText());
  tokens += information.utilization.total_tokens;
  const content material = JSON.parse(information.decisions[0].message.content material);
  return content material;
};

5. Course of Spam Emails and e mail the Report

You may run this Google script manually or arrange a cron set off to run it mechanically at common intervals. It marks the spam emails as learn in order that they aren’t processed once more.

const SPAM_THRESHOLD = 2; 

const reportFalsePositives = () => {
  const html = [];
  const threads = getSpamThreads_();
  for (let i = 0; i < threads.size; i += 1) {
    const [message] = threads[i].getMessages();
    const messagePrompt = getMessagePrompt_(message);
    
    const { spam_score, abstract } = getMessageScore_(messagePrompt);
    if (spam_score <= SPAM_THRESHOLD) {
      
      html.push(`${message.getFrom()} ${abstract}`);
    }
  }
  threads.forEach((thread) => thread.markRead()); 
  if (html.size > 0) {
    const htmlBody = [
      ``,'',
      html.join(''),'
Email SenderSummary
'
, ].be part of(''); const topic = `Gmail Spam Report - ${tokens} tokens used`; GmailApp.sendEmail(USER_EMAIL, topic, '', { htmlBody }); } };

Additionally see: Authenticate your Gmail messages

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *