A Python script that authenticates via OAuth 2.0, retrieves the latest Gmail messages (subject, from, date, id, snippet), and saves them to a JSON file (e.g., emails.json). The access token is cached locally in token.json.
- OAuth 2.0 authorization (token cached in
token.json) - Read-only scope: https://www.googleapis.com/auth/gmail.readonly
- Fetches the latest 5 messages (adjust in code if needed)
- Python 3.10+ (3.13 recommended)
- Dependencies from
requirements.txt credentials.json(OAuth 2.0 client) in the project root
# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt- Go to Google Cloud Console.
- Create a project (or select an existing one).
- Enable Gmail API: "APIs & Services" → "Library" → search "Gmail API" → "Enable".
- Open "APIs & Services" → "Credentials".
- Click "Create credentials" → "OAuth client ID".
- If prompted, configure the OAuth consent screen (minimum: app name and email).
- Choose application type: "Desktop application" (for local script).
- Download the JSON and save it as
credentials.json. - Place
credentials.jsonin the project root (next tomain.py).
python main.pyOn the first run, a browser window will open for authorization. After successful authorization, a token will be saved to token.json.
The script saves the latest messages to emails.json in JSON format with fields: subject, from, date, id, snippet.