로드 중...
검색 결과가 없습니다.

Google Cloud Skills Boost

Google Cloud 콘솔에서 기술 적용


700개 이상의 실습 및 과정 이용하기

Gmail Sentiment Analysis with Gemini and Vertex AI

실습 1시간 30분 universal_currency_alt 크레딧 1개 show_chart 입문
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
700개 이상의 실습 및 과정 이용하기

GSP1301

Overview

Add-ins can extend Google Workspace capabilities to help Google Workspace users be more productive and improve their workflow. In this lab, you build a Google Workspace add-on that leverages the power of Gemini and Vertex AI to conduct sentiment analysis for Gmail. You set up the necessary cloud resources (including the Vertex AI APIs), configure an Apps Script project, and to deploy the add-on.

The add-on allows you to automatically identify and label emails with a negative tone. You can use it to prioritize customer service responses or quickly identify potentially sensitive emails.

By the end of the lab, you'll have a functional tool that demonstrates the practical application of AI for enhancing productivity and communication within a business context.

What you'll learn

In this lab, you do the following:

  • Build a Google Workspace add-on that extends Gmail's functionality.
  • Integrate Vertex AI with Google Workspace to use Gemini and Vertex AI's natural language processing capabilities within a Gmail add-on.
  • Implement OAuth2 authentication to securely authorize the add-on to access user data.
  • Apply sentiment analysis to programmatically analyze email content to determine emotional tone.
  • Utilize Apps Script Write code to interact with Gmail, manage user interfaces, and connect to external APIs.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the left is the Lab Details pane with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details pane.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details pane.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field.

Task 1. Access your lab environment

You've signed into the Google Cloud console. Now you sign into Gmail.

  1. Click Open Gmail to open the Gmail sign-in page.

Tip: Arrange the tabs in separate windows for easier viewing.

  1. Sign in to Gmail using the Username, and the Password, .
Note: These credentials are also in the Lab details pane and were used to sign in to the Google Cloud console.
  1. Once you're in Gmail, click Get started and close any informational windows. You should now see your Inbox.

You're all set to begin the lab activities!

Task 2. Configure your Google Cloud environment

In this task you enable the Vertex AI API and then configure OAuth consent screen to define what Google Workspace displays to users.

Enable Vertex AI API

  1. In Google Cloud console, in the Navigation menu, click APIs and Services > Library.

  2. Type Vertex AI API into the Search for APIs & Services box, and then click Vertex AI API in the search results.

  3. Click Enable to enable the API.

The API/Service Details page opens.

Configure the OAuth consent screen

  1. In the left pane, click OAuth consent screen.

  2. Click Get Started.

  3. For App Information, set the following and then click Next:

  • App name: Gmail Sentiment Analysis with Gemini and Vertex AI
  • User support email:
  1. For Audience, select Internal and then click Next.
  2. For Contact Information, set Email addresses to and then click Next.
  3. For Finish, agree to the Google API Services: User Data Policy, then click Continue.
  4. Click Create.

Click Check my progress to verify the objective. Configure the OAuth consent screen.

Task 3. Set up the Apps Script project

In this task, you create and configure your add-on as an Apps Script project.

Get your Google Cloud project number

To get your Google Cloud project number to use when you create an Apps Script project:

  1. In the Navigation menu () click Cloud overview > Dashboard.

  2. From the Project info section, record the Project number to use later in this lab.

Create an Apps Script project

  1. In the Student Resources pane, click this link, script.google.com/ to open the Apps Script page.

  2. Click New project to create an Apps Script project.

  3. Name your project:

    • Click "Untitled project" at the upper left.
    • Name the project Gmail Sentiment Analysis with Gemini and Vertex AI, then click Rename.
  4. Make the manifest file visible:

    • In the left pane, click Project Settings ().
    • Select Show 'appsscript.json' manifest file in editor.
  5. Change your Google Cloud Platform project:

    • Scroll further down to the Google Cloud Platform (GCP) Project section and click Change project.
    • Set the GCP project number to the project number you previously recorded.
    • Click Set project.

Click Check my progress to verify the objective. Create an Apps Script project.

Task 4. Populate code files

  • In the left pane, click Editor () to open the editor window.

Follow the instructions below to update your project with the sample code.

appsscript.json

  1. Open appsscript.json and replace its file contents with the following:
{ "timeZone": "America/Toronto", "oauthScopes": [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/gmail.addons.execute", "https://www.googleapis.com/auth/gmail.labels", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/userinfo.email" ], "addOns": { "common": { "name": "Sentiment Analysis", "logoUrl": "https://fonts.gstatic.com/s/i/googlematerialicons/sentiment_extremely_dissatisfied/v6/black-24dp/1x/gm_sentiment_extremely_dissatisfied_black_24dp.png" }, "gmail": { "homepageTrigger": { "runFunction": "onHomepageTrigger", "enabled": true } } }, "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8" }
  1. Click Save to save your project.

Code.gs

  1. Open Code.gs and replace its contents with the following:
/* Copyright 2024-2025 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Replace with your project ID const PROJECT_ID = '{{{project_0.project_id | Project ID}}}'; // Location for your Vertex AI model const VERTEX_AI_LOCATION = 'us-east4'; // Model ID to use for sentiment analysis const MODEL_ID = 'gemini-2.0-flash'; /** * Triggered when the add-on is opened from the Gmail homepage. * * @param {Object} e - The event object. * @returns {Card} - The homepage card. */ function onHomepageTrigger(e) { return buildHomepageCard(); } /** * Builds the main card displayed on the Gmail homepage. * * @returns {Card} - The homepage card. */ function buildHomepageCard() { // Create a new card builder const cardBuilder = CardService.newCardBuilder(); // Create a card header const cardHeader = CardService.newCardHeader(); cardHeader.setImageUrl('https://fonts.gstatic.com/s/i/googlematerialicons/mail/v6/black-24dp/1x/gm_mail_black_24dp.png'); cardHeader.setImageStyle(CardService.ImageStyle.CIRCLE); cardHeader.setTitle("Analyze your Gmail"); // Add the header to the card cardBuilder.setHeader(cardHeader); // Create a card section const cardSection = CardService.newCardSection(); // Create buttons for generating sample emails and analyzing sentiment const buttonSet = CardService.newButtonSet(); // Create "Generate sample emails" button const generateButton = createFilledButton('Generate sample emails', 'generateSampleEmails', '#34A853'); buttonSet.addButton(generateButton); // Create "Analyze emails" button const analyzeButton = createFilledButton('Analyze emails', 'analyzeSentiment', '#FF0000'); buttonSet.addButton(analyzeButton); // Add the button set to the section cardSection.addWidget(buttonSet); // Add the section to the card cardBuilder.addSection(cardSection); // Build and return the card return cardBuilder.build(); } /** * Creates a filled text button with the specified text, function, and color. * * @param {string} text - The text to display on the button. * @param {string} functionName - The name of the function to call when the button is clicked. * @param {string} color - The background color of the button. * @returns {TextButton} - The created text button. */ function createFilledButton(text, functionName, color) { // Create a new text button const textButton = CardService.newTextButton(); // Set the button text textButton.setText(text); // Set the action to perform when the button is clicked const action = CardService.newAction(); action.setFunctionName(functionName); textButton.setOnClickAction(action); // Set the button style to filled textButton.setTextButtonStyle(CardService.TextButtonStyle.FILLED); // Set the background color textButton.setBackgroundColor(color); return textButton; } /** * Creates a notification response with the specified text. * * @param {string} notificationText - The text to display in the notification. * @returns {ActionResponse} - The created action response. */ function buildNotificationResponse(notificationText) { // Create a new notification const notification = CardService.newNotification(); notification.setText(notificationText); // Create a new action response builder const actionResponseBuilder = CardService.newActionResponseBuilder(); // Set the notification for the action response actionResponseBuilder.setNotification(notification); // Build and return the action response return actionResponseBuilder.build(); } /** * Generates sample emails for testing the sentiment analysis. * * @returns {ActionResponse} - A notification confirming email generation. */ function generateSampleEmails() { // Get the current user's email address const userEmail = Session.getActiveUser().getEmail(); // Define sample emails const sampleEmails = [ { subject: 'Thank you for amazing service!', body: 'Hi, I really enjoyed working with you. Thank you again!', name: 'Customer A' }, { subject: 'Request for information', body: 'Hello, I need more information on your recent product launch. Thank you.', name: 'Customer B' }, { subject: 'Complaint!', body: '', htmlBody: `

Hello, You are late in delivery, again.

Please contact me ASAP before I cancel our subscription.

`, name: 'Customer C' } ]; // Send each sample email for (const email of sampleEmails) { GmailApp.sendEmail(userEmail, email.subject, email.body, { name: email.name, htmlBody: email.htmlBody }); } // Return a notification return buildNotificationResponse("Successfully generated sample emails"); } /** * Analyzes the sentiment of the first 10 threads in the inbox * and labels them accordingly. * * @returns {ActionResponse} - A notification confirming completion. */ function analyzeSentiment() { // Analyze and label emails analyzeAndLabelEmailSentiment(); // Return a notification return buildNotificationResponse("Successfully completed sentiment analysis"); } /** * Analyzes the sentiment of emails and applies appropriate labels. */ function analyzeAndLabelEmailSentiment() { // Define label names const labelNames = ["HAPPY TONE 😊", "NEUTRAL TONE 😐", "UPSET TONE 😡"]; // Get or create labels for each sentiment const positiveLabel = GmailApp.getUserLabelByName(labelNames[0]) || GmailApp.createLabel(labelNames[0]); const neutralLabel = GmailApp.getUserLabelByName(labelNames[1]) || GmailApp.createLabel(labelNames[1]); const negativeLabel = GmailApp.getUserLabelByName(labelNames[2]) || GmailApp.createLabel(labelNames[2]); // Get the first 10 threads in the inbox const threads = GmailApp.getInboxThreads(0, 10); // Iterate through each thread for (const thread of threads) { // Iterate through each message in the thread const messages = thread.getMessages(); for (const message of messages) { // Get the plain text body of the message const emailBody = message.getPlainBody(); // Analyze the sentiment of the email body const sentiment = processSentiment(emailBody); // Apply the appropriate label based on the sentiment if (sentiment === 'positive') { thread.addLabel(positiveLabel); } else if (sentiment === 'neutral') { thread.addLabel(neutralLabel); } else if (sentiment === 'negative') { thread.addLabel(negativeLabel); } } } } /** * Sends the email text to Vertex AI for sentiment analysis. * * @param {string} emailText - The text of the email to analyze. * @returns {string} - The sentiment of the email ('positive', 'negative', or 'neutral'). */ function processSentiment(emailText) { // Construct the API endpoint URL const apiUrl = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:generateContent`; // Prepare the request payload const payload = { contents: [ { role: "user", parts: [ { text: `Analyze the sentiment of the following message: ${emailText}` } ] } ], generationConfig: { temperature: 0.9, maxOutputTokens: 1024, responseMimeType: "application/json", // Expected response format for simpler parsing. responseSchema: { type: "object", properties: { response: { type: "string", enum: ["positive", "negative", "neutral"] } } } } }; // Prepare the request options const options = { method: 'POST', headers: { 'Authorization': `Bearer ${ScriptApp.getOAuthToken()}` }, contentType: 'application/json', muteHttpExceptions: true, // Set to true to inspect the error response payload: JSON.stringify(payload) }; // Make the API request const response = UrlFetchApp.fetch(apiUrl, options); // Parse the response. There are two levels of JSON responses to parse. const parsedResponse = JSON.parse(response.getContentText()); const sentimentResponse = JSON.parse(parsedResponse.candidates[0].content.parts[0].text).response; // Return the sentiment return sentimentResponse; }

Click Save to save your project.

Task 5. Deploy the add-on

In this task you deploy the add-on, then verify the installation.

Deploy the add-on

  1. In the title bar, click Deploy > Test deployments.

  2. Confirm Gmail is listed for Application(s) and click Install.

  3. Click Done.

Verify the installation

  • Refresh the Gmail tab. You should see an icon in the right pane.

Troubleshoot

If you don't see your add-on in the list, refresh the browser window.

If it's still not there, go back to the Apps Script project, uninstall the add-on from the Test deployments window, and then reinstall it.

Task 6. Run the add-on

You're ready to run the add-on! In this task you open and authorize the add-on, then generate emails to verify that the analysis works.

  1. Still in Gmail, in the right pane, click Sentiment Analysis ().

  2. When the side panel opens, click Authorize access to grant the add-on permission to run.

A consent screen opens. Select your email () and click through the screens to allow access.

Once you have granted consent, the Sentiment Analysis pane opens on the right.

  1. In the Sentiment Analysis pane, click Generate sample emails.

The add-on now generates sample emails to test the analysis. A message will be displayed once the generation has completed, which only takes a few seconds.

  1. Wait for the sample emails to show-up in your inbox. You may have to refresh your inbox to see the new emails.

  2. Once the sample emails are in your inbox, in the Sentiment Analysis pane, click Analyze emails.

A message that the analysis has been completed shows on the bottom of the add-on screen.

Note :Analyzing emails can take a while. You can refresh the page to check the status of applied labels.

The add-on analyzes your emails and applies the appropriate label ("HAPPY TONE 😊", "UPSET TONE 😡" or "NEUTRAL TONE 😐") to messages in your inbox.

You may have to refresh your Gmail to see the applied labels.

  1. Continue to Experiment You can test the add-on by sending emails with varying sentiments (positive, negative, neutral) from your lab Gmail to another lab Gmail account. External emails are not permitted. Observe how the add-on analyzes and labels each email.
NOTE: The code only pulls the last 10 emails from your inbox, but you can change that value.
  1. Close the add-on: Once you are finished with the add-on, you can now close the add-on by clicking the X in the top right corner of the side panel.

Click Check my progress to verify the objective. Apply sentiment analysis.

Congratulations!

You've successfully completed the Gmail Sentiment Analysis with Gemini and Vertex AI lab.

In this lab, you learned how to:

  • Build a Google Workspace add-on: Develop a practical tool that extends Gmail's functionality.
  • Integrate Vertex AI with Google Workspace: Use Gemini and Vertex AI's natural language processing capabilities within a Gmail add-on.
  • Implement OAuth2 authentication: Securely authorize the add-on to access user data.
  • Apply sentiment analysis: Programmatically analyze email content to determine emotional tone.
  • Utilize Apps Script: Write code to interact with Gmail and , manage user interfaces., and connect to external APIs.

You now have a functional Gmail add-on that can help you prioritize emails and improve your workflow. Feel free to experiment further with the add-on—perhaps by customizing the sentiment analysis or adding new features.

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated March 25, 2025

Lab Last Tested February 25, 2025

Copyright 2025 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

시작하기 전에

  1. 실습에서는 정해진 기간 동안 Google Cloud 프로젝트와 리소스를 만듭니다.
  2. 실습에는 시간 제한이 있으며 일시중지 기능이 없습니다. 실습을 종료하면 처음부터 다시 시작해야 합니다.
  3. 화면 왼쪽 상단에서 실습 시작을 클릭하여 시작합니다.

현재 이 콘텐츠를 이용할 수 없습니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

감사합니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

한 번에 실습 1개만 가능

모든 기존 실습을 종료하고 이 실습을 시작할지 확인하세요.

시크릿 브라우징을 사용하여 실습 실행하기

이 실습을 실행하려면 시크릿 모드 또는 시크릿 브라우저 창을 사용하세요. 개인 계정과 학생 계정 간의 충돌로 개인 계정에 추가 요금이 발생하는 일을 방지해 줍니다.