Automate Gmail with Google Apps Script & Gemini AI | Full Tutorial
Key Takeaways
This video tutorial demonstrates how to automate Gmail with Google Apps Script and Gemini AI, covering topics such as email analysis, labeling, and automation using AI tools. It provides a step-by-step guide on how to build a powerful AI assistant to automatically filter and label important emails in Gmail.
Full Transcript
Hey everyone and welcome back to the channel. In this video, we are going to explore how we can leverage Google's Gemini AI and Appcript to automate the organization of our email inboxes. We're going to send the content of our messages to Gemini. Gemini is going to review that message and make a decision based on whether that message requires our attention. And if it does, we're going to use Appcript to automatically tag that message in Gmail. I think this is going to be a super interesting project and give us inspiration about other ways we can leverage Gemini combined with appcript and automation. So let's get started. To start, open a new appcript project at script.google.com. And then we need to select new project. And in your code.gs file, let's start by deleting this existing code and then defining a new function. And this function is going to be called get unprocessed emails. And this function is going to be super simple. Let's start by typing in return. And now we need to choose what we want to be returned. So to do this, we're going to use the Gmail app service which is going to run this search. And then we're going to use the search method. And we need to provide this method some parameters. And the first one is a query string. And for this query, we're going to look for two things. The first is unread as we only want to look at unread messages. And we're also going to use a label. And this label is going to be called processed. And the reason I included a minus sign here is we're looking for messages that aren't labeled as processed. Okay. Now, let's define a new function to test this out. This is going to be called test reading emails. Then I'm going to define a new variable called threads. And this variable is going to call the function we defined up here. And then we're going to loop through the results using for define a new variable called thread of threads. So looking at each thread within that array of threads we're going to get. And then we're simply just going to log this to the console to make sure it's all working properly. So let's use our Fred variable here and we're going to get the first message subject for each of those. Okay, let's now press save and run our test reading emails function. It's the first time we've run this, so of course we need to review permissions, select our account, and press continue. And here we go. It's returned every message I've got in my inbox. Not too many actually. One small change we're going to make. Rather than turning my entire inbox, I just want to limit it to the last five messages while we're testing this out. Okay, let's just try this again. And we should see only five messages being returned this time. Perfect. Okay, now that's done. Now for the exciting part. We're going to send all of our email content to Gemini AI and ask it to analyze each one for us with a very precise prompt. First of all, we need to go to Google AI Studio by going to astudio.google.com in order to get an API key, which is like a secret password that lets our script talk to the AI. So once you get here, go on to the left hand side and select get API key and then on the top right, select create API key. If you've never created one here before, you can have Gemini create a Google Cloud project for you or you can select an existing project as well. Okay, once we've got our API key, let's copy this and then go back to our Appcript project. On the left hand side, select project settings. Scroll down and add a new script property. And we're going to call this property Gemini API_key. and then paste our key into here and press save. Okay, now that's done, let's go back to our code. And now to save time, I'm just going to copy and paste this code in. So let's do that now and talk through what's happening here. So I've defined a new function here called get email analysis and we're going to pass this function a message. The first thing we're doing here is getting our API key from the script properties which we just saved a moment ago. Then we're assigning the model we want to use. In this case, we're just going to use Gemini 1.5 Flash along with the URL we're going to use. But the real magic here is our prompt. In this prompt, we're giving Gemini a very detailed set of rules telling it exactly what to look for and what to ignore. So in this case, at a high level, we're telling Gemini to analyze our email and determine if it requires our direct action. And we're also telling Gemini how to format that answer. In this case, we want it formatted as a JSON object with just one key. And that one key is going to be called require response. And it's going to be a boolean value, so true or false. Then further down here, we're just setting out some conditions about what emails do or do not require our response. And you might remember further up here, we're passing it our message into this function. So within this prompt, we're including the message subject and the message text. So that's all getting passed to Gemini as part of this prompt. Next, we package up that prompt into our payload and define some options for our web request as well. And then we're using URL fetch app to send all of this information to the Gemini API. When Gemini sends this response back, it's wrapped in a lot of extra data. So the last few lines here are just cleaning up that data. We pass the response, dig into the data structure to find the part that contains the AI's actual text. We clean it up, pass it one last time, and then turn it into a nice, clean, usable JavaScript object. Now that our AI can analyze emails, let's take action by applying labels. Before we write the code, go into Gmail and we need to create two new labels. These labels are going to be called processed and another called to respond. Now, let's write a function that takes the AI's analysis and applies the correct labels. This function is going to be called apply Gmail labels and it's going to accept two parameters. One called threads for our message thread and another called analysis which of course is our analysis from Gemini. First, let's define a new variable called subject. And this is going to be equal to Fred get first message subject. And we're just going to get this to write to our console log so we know which Gmail is being updated. So just forformational purposes really. Now let's define an if statement. So let's type in if open brackets analysis dot requires response. Remember analysis is the object being returned from Gemini AI in this function above called get email analysis and it's either going to be true or false but if it's true what we're going to do is firstly let's just make one more variable called to respond label and then we need to get that label information from Gmail app again and we're going to use the get user label by name method and then just provide its name. And the label we just created was called to respond. And then we're going to get Fred and use add label. And next we need to apply the label to that message. So to do this, let's type in Fred to get the message thread and then add label and open brackets and then use this variable we just created above to apply that label. And let's write this to the console log as well. So to do that, let's type in console.log open brackets back tick email. And then this is where we're going to use the subject. So let's use a dollar sign and curly brackets subject labeled as to respond. So this section of code is applying the to respond label if the Gemini decision comes back as true. I also want to do the same thing down here. So, I'm just going to copy this code, but adjust this to also apply the processed label. And remember, the processed label is just to ensure that we are only checking a message once. We're not going to repeatedly check the same message. So, we use a process label to track that. So, what I need to do here now is change this to processed. Let's change this variable name as well to process label. So now we've got our variable called process label. Let's also insert this down here and also just update what we're writing to the console log. So great, now we're adding this processed label at the end here. And again, this is just how we prevent the script from analyzing the same email over and over again on future runs because of course we're filtering out emails which already have the processed label. Okay, let's now press save. Always good practice to save lots and then continue on. We just need to define one more function to bring this all together. So I'm going to go back up to the top here. This is going to be our main function which is using all of these helper functions we've just created. This function is going to be called process inbox. And you guessed it, it's going to process our inbox. And the first thing it's going to do is we're going to use this line again which we wrote earlier. Uh we're going to define a new variable called threads which calls our function down here to get all of the unprocessed email which is unread. And again just like before in our test function we're going to loop through each of those messages in those threads. Let's delete this line which is just logging this to the console. And what we're going to do is I'm going to firstly define a try catch block. And this is just a way of handling errors. So the code we want to run goes in the try block, but if it fails, then we can log that error in our catch block. So in here, let's define another new variable. This one's going to be called message. We're going to call the Fred variable and get uh the messages. And then once we've got that message, I'm going to define another new variable. This one's called analysis. And this is where we're going to call our get email analysis function. So this is just defined down here. So let's copy this now. So then we're sending our message contents to our analysis function which will then send that out to Gemini AI and return a decision to us. And then if analysis is true, we're going to call the apply Gmail labels function and pass it the Fred and the analysis. And then just in case anything doesn't work, let's log our errors to the console as well. So I'm just going to copy in this line to save a bit of time. Okay, that's it. So now it's time to test out this function. So I've saved my code. Now let's select the process inbox function and press run. Okay, we need to review our permissions again as we've made some changes since we last ran this. So let's select our account and press continue. So now each message is being sent to Gemini for analysis. Gemini is making a decision for us and then assigning the proper label. So now if we jump over to Gmail, I've switched over to Gmail now and as you can see we've got five messages at the top all marked as processed and it's correctly identified the messages I need to respond to. I can also see this on the left hand side here under my labels. I can see I've got five messages all processed and these two are marked as to respond. So if we check the message contents, these are clearly messages asking for me to action something whereas some of these other messages are just notifications like the sharing notification and this calendar invite here. So the Gemini prompt we've provided is actually done a nice job of correctly identifying the emails that we need to action. And to make this fully automated, we can add a trigger on the left hand side by going to triggers. And then let's select add trigger down on the bottom right. We're going to select our process inbox function. We want this to be time driven. And we want it to run this function maybe every hour or every 30 minutes depending on how busy your inbox is. And then press save. So now this is going to run automatically and keep your email organized 24/7. I hope this inspires you to think about what you can automate in your own workflow. If you found this tutorial helpful, please hit that like button and subscribe for more. Thanks for watching and happy scripting.
Original Description
In this full tutorial, I'll show you how to build a powerful AI assistant with Google Apps Script and Gemini to automatically filter and label your important emails in Gmail. Stop manually organizing and start automating! 🤖⚙️
We'll go step-by-step, from reading your inbox with a simple script to programming the Gemini AI with a custom prompt to identify what's important and what's just noise. By the end, you'll have an intelligent, automated workflow that finds and labels emails requiring your action, saving you hours of work and stress.
This is the ultimate guide to Gmail automation and a perfect project to level up your Google Apps Script skills.
🔗 Get the complete, final script here:
https://github.com/peterghorner-scripts/gemini-gmail-automation/blob/main/Code.gs
## Chapters
0:00 - Intro: Building an AI to Organize Your Inbox
0:40 - Step 1: Reading Emails with Google Apps Script
3:18 - Step 2: Getting Your Gemini AI API Key in Google AI Studio
3:15 - Storing Your API Key Securely
4:17 - The AI Analysis Function & Custom Prompt
6:25 - Step 3: Applying "Processed" & "To Respond" Labels
10:00 - Step 4: Assembling the Final Script
12:24 - Final Demo & How to Set Up a Trigger
## Disclaimer
This script uses the Google AI (Gemini) API, which may be a paid service depending on your usage. Please review Google's pricing before implementing. Never share your API key publicly.
#GoogleAppsScript #GeminiAI #Gmail #Automation #Productivity #GoogleWorkspace #InboxZero #AppsScript #AIassistant
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
More on: Prompt Craft
View skill →Related Reads
📰
📰
📰
📰
My first weekend challenge
Dev.to · Dina
Nomad AI Review 2026: Can This AI-Powered Travel Platform Help You Build an Online Business?
Medium · AI
The Only 4 Claude Prompts I Use Every Single Day
Medium · Programming
The Most Valuable Way to Use AI in Your Business Is Also the Most Boring
Medium · AI
Chapters (8)
Intro: Building an AI to Organize Your Inbox
0:40
Step 1: Reading Emails with Google Apps Script
3:18
Step 2: Getting Your Gemini AI API Key in Google AI Studio
3:15
Storing Your API Key Securely
4:17
The AI Analysis Function & Custom Prompt
6:25
Step 3: Applying "Processed" & "To Respond" Labels
10:00
Step 4: Assembling the Final Script
12:24
Final Demo & How to Set Up a Trigger
🎓
Tutor Explanation
DeepCamp AI