Search Email with GMail API

 
import os
import json
import requests
from fastapi import FastAPI, HTTPException, Request, Depends, status
from fastapi.responses import JSONResponse, RedirectResponse
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request as GoogleRequest
from googleapiclient.discovery import build
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import Response

app = FastAPI()
app.credentials = None

CLIENT_ID = os.environ["CLIENT_ID"]
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
REDIRECT_URI = os.environ["REDIRECT_URI"]
SCOPE = "https://www.googleapis.com/auth/gmail.readonly"

from pydantic import BaseModel

About this template

This is a FastAPI-based application that uses Google’s Gmail API to fetch and display emails based on user-defined search queries. It provides a /search_emails endpoint for email searches and a /oauth2callback endpoint for OAuth2 callbacks. The app requires the environment variables CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI for OAuth2 authentication. These credentials pertain to your Google API and must be set correctly for the application to function as expected.

Introduction to the Search Email with Gmail API Template

Welcome to the step-by-step guide on how to use the "Search Email with Gmail API" template on Lazy. This template is designed to help you build an application that can fetch and display emails from a Gmail account based on user-defined search queries. It leverages the Gmail API and FastAPI to create a robust backend service that can be integrated with other applications or used as a standalone tool.

Getting Started

To begin using this template, simply click on "Start with this Template" on the Lazy platform. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy or paste any code manually.

Initial Setup

Before you can test and use the application, you need to set up some environment secrets within the Lazy Builder. These are necessary for OAuth2 authentication with the Gmail API. Here's what you need to do:

  • Go to the "Environment Secrets" tab in the Lazy Builder.
  • Set the following secrets with the respective values from your Google API credentials:
    • CLIENT_ID: Your Google API client ID.
    • CLIENT_SECRET: Your Google API client secret.
    • REDIRECT_URI: The URI where you will receive the OAuth2 callback.
  • To obtain these values, you need to create a project in the Google Developers Console, enable the Gmail API, and set up the OAuth consent screen. Then, create credentials for an OAuth 2.0 client ID, where you will get the CLIENT_ID and CLIENT_SECRET. The REDIRECT_URI will be the endpoint in your application that receives the authentication code from Google.

For detailed instructions on setting up your Google API credentials, please refer to the Google Cloud documentation.

Test: Pressing the Test Button

Once you have set up the environment secrets, you can press the "Test" button on the Lazy platform. This will deploy your application and launch the Lazy CLI. If the application requires any user input, you will be prompted to provide it through the Lazy CLI.

Using the App

After deployment, Lazy will provide you with a dedicated server link to use the API. If you're using FastAPI, you will also receive a link to the API documentation, which will help you understand the available endpoints and how to interact with them.

To search for emails, you will use the /search_emails endpoint. You can send a POST request to this endpoint with a JSON body containing the search query parameters. Here's an example of a search query:


{
  "query": {
    "from": "example@example.com",
    "subject": "meeting"
  }
}

The response will include a list of emails that match your search criteria, including details like the email's subject, body, and date.

Integrating the App

If you wish to integrate this backend service with a frontend or another tool, you can use the server link provided by Lazy. For instance, you can make HTTP requests from your frontend application to the deployed server to search and display emails.

Remember to handle the OAuth2 authentication flow in your frontend by redirecting users to the /oauth2callback endpoint and handling the authentication code that Google provides.

By following these steps, you should be able to set up and use the "Search Email with Gmail API" template on Lazy to create an application that interacts with the Gmail API to search and display emails based on user-defined queries.

Category
Last published
May 20, 2024

More templates like this

GPT-4 Exam Generator

This app uses GPT-4 to generate a PDF of a new exam based on an uploaded PDF of a past exam.

PDF
OpenAI
Python

Job Search Website

A customisable one-page job search website with a search bar and a search button that displays UI cards of matching jobs. You need to have a (free) account on https://rapidapi.com/ to get the API key required for this to work.

React JS
Python
Flask
HTML
CSS

CSV Deduper

A webpage that dedupes a CSV based on the values in the first column and allows for downloading.

Python
Flask
Home
/
Search Email with GMail API