0Pricing
AI Agents · レッスン

API経由でGmailに接続する

Google APIクライアントライブラリ、OAuth2同意画面、Gmailスコープの選択を学びます。

「API経由でGmailに接続する」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

SMTPではなくGmail APIを使う理由

従来のメール自動化ではSMTP/IMAPを使用しますが、Gmail APIには、スレッドの読み取り、クエリによる検索、ラベルの管理、完全な認証による送信など、さらに多くの機能があります。また、OAuth 2.0をサポートしているため、エージェントがパスワードを保存する必要はありません。保存するのは、スコープが制限されたアクセストークンだけです。

Gmail APIはGoogle Workspace APIsの一部であり、google-api-python-clientライブラリを介して利用します。

# Install required libraries:
# pip install google-api-python-client google-auth google-auth-oauthlib

# The Gmail API lets agents:
# - List and search messages (labels, queries)
# - Read full message content and attachments
# - Send messages via OAuth (no password needed)
# - Manage labels and threads
# - Watch for new messages via push notifications

print('Gmail API is part of Google Workspace APIs')

認証:サービスアカウントとユーザー認証

Gmail APIには、次の2つの認証方法があります。

  • Service Account:ドメイン全体の委任を使用するワークスペースや組織での利用に最適です。ユーザーの操作は必要ありません
  • User OAuth (OAuth2 with consent screen):個人のGmailアカウントで必要です。ユーザーが一度アクセスを許可し、エージェントはリフレッシュトークンを使用します

多くのエージェント自動化では、信頼性の高さからサービスアカウントが推奨されます。

# Service Account approach:
# 1. Go to Google Cloud Console -> APIs & Services -> Credentials
# 2. Create a Service Account
# 3. Download the JSON key file
# 4. In Google Workspace Admin: enable domain-wide delegation
# 5. Grant required scopes to the service account

# User OAuth approach:
# 1. Create OAuth 2.0 Client ID (Desktop or Web App type)
# 2. Download credentials.json
# 3. First run: user sees consent screen and grants access
# 4. Agent stores token.json with refresh token for subsequent runs

print('Choose service account for org automation, OAuth for personal Gmail')

OAuth2認証情報JSONの構造

Googleは、エージェントが認証に使用する認証情報をJSONファイルで提供します。User OAuthでは、Google Cloud Consoleからダウンロードしたcredentials.jsonファイルを使用します。このファイルにはクライアントID、シークレット、リダイレクトURIが含まれるため、バージョン管理システムには絶対にコミットしないでください。

# credentials.json structure (User OAuth — Desktop app type):
# {
#   "installed": {
#     "client_id": "123456789.apps.googleusercontent.com",
#     "client_secret": "GOCSPX-abc123xyz",
#     "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"],
#     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#     "token_uri": "https://oauth2.googleapis.com/token"
#   }
# }

# service-account.json structure:
# {
#   "type": "service_account",
#   "project_id": "my-project",
#   "private_key_id": "abc123",
#   "private_key": "-----BEGIN PRIVATE KEY-----\n...",
#   "client_email": "agent@my-project.iam.gserviceaccount.com",
#   "client_id": "..."
# }

print('Store credential files outside your git repository')

Gmail APIのスコープ

OAuthのスコープは、エージェントがアクセスできる範囲を正確に定義します。必要なスコープだけを要求してください。これは最小権限の原則です。Gmailのスコープには、読み取り専用から完全なアクセスまでの種類があります。

  • gmail.readonly — すべてのメールを読み取る
  • gmail.send — 送信のみ。読み取りは不可
  • gmail.modify — 読み取り、送信、ラベルの変更
  • gmail.compose — 下書きの作成のみ
# Gmail API scope constants
SCOPE_READONLY = 'https://www.googleapis.com/auth/gmail.readonly'
SCOPE_SEND = 'https://www.googleapis.com/auth/gmail.send'
SCOPE_MODIFY = 'https://www.googleapis.com/auth/gmail.modify'
SCOPE_COMPOSE = 'https://www.googleapis.com/auth/gmail.compose'

# Calendar scopes (often used alongside Gmail)
SCOPE_CALENDAR_READ = 'https://www.googleapis.com/auth/calendar.readonly'
SCOPE_CALENDAR_EVENTS = 'https://www.googleapis.com/auth/calendar.events'

# Combine scopes your agent actually needs
AGENT_SCOPES = [
    SCOPE_READONLY,
    SCOPE_SEND,
    SCOPE_CALENDAR_EVENTS
]
print(f'Using {len(AGENT_SCOPES)} scopes')

ユーザーOAuth:初回認証フロー

ユーザーが初めてエージェントを実行すると、権限を許可するためのブラウザが開きます。エージェントは、その結果取得したトークンをtoken.jsonに保存します。次回以降の実行では、保存済みのトークンを読み込み、自動的に更新するため、ブラウザ操作は必要ありません。

from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import os

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_credentials(token_file='token.json', creds_file='credentials.json'):
    creds = None

    # Load existing token if available
    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file, SCOPES)

    # Refresh or re-authenticate if needed
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())  # auto-refresh
        else:
            # Opens browser for user consent (first time only)
            flow = InstalledAppFlow.from_client_secrets_file(
                creds_file, SCOPES
            )
            creds = flow.run_local_server(port=0)
        # Save token for next run
        with open(token_file, 'w') as f:
            f.write(creds.to_json())

    return creds

サービスアカウント認証

ユーザーの操作なしで実行する自動化エージェントには、サービスアカウントが最適です。エージェントは秘密鍵で認証し、ドメイン全体の委任を介してGoogle Workspaceユーザーを偽装します。同意画面もブラウザも必要なく、JSONキーファイルだけで済みます。

from google.oauth2 import service_account
import os

SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send'
]

def get_service_account_credentials(impersonate_user):
    service_account_file = os.environ.get(
        'GOOGLE_SERVICE_ACCOUNT_JSON',
        'service-account.json'
    )

    credentials = service_account.Credentials.from_service_account_file(
        service_account_file,
        scopes=SCOPES
    )

    # Impersonate a real user (requires domain-wide delegation in Admin)
    delegated = credentials.with_subject(impersonate_user)
    return delegated

creds = get_service_account_credentials('agent@yourcompany.com')
print('Service account credentials ready')

Gmailサービスオブジェクトの構築

認証情報を取得したら、googleapiclient.discovery.build()を使用してGmailサービスオブジェクトを作成します。これは、すべてのGmail API呼び出しで使用する主要なインターフェースです。サービス名'gmail'とバージョン'v1'を渡してください。

from googleapiclient.discovery import build

def build_gmail_service(credentials):
    service = build(
        'gmail',
        'v1',
        credentials=credentials,
        cache_discovery=False  # avoid file warnings in some environments
    )
    return service

# Full setup: credentials -> service
creds = get_credentials()          # or get_service_account_credentials()
gmail = build_gmail_service(creds)

# Test: get user profile
profile = gmail.users().getProfile(userId='me').execute()
print('Email:', profile['emailAddress'])
print('Total messages:', profile['messagesTotal'])

Calendarサービスオブジェクトの構築

Google Calendarでも同じ認証情報の設定を使用できます。'calendar'と'v3'を指定して構築するだけです。1つのエージェントでGmailとCalendarの両方が必要な場合は、同じ認証情報オブジェクトから両方のサービスを構築してください。

from googleapiclient.discovery import build

def build_google_services(credentials):
    gmail = build(
        'gmail', 'v1',
        credentials=credentials,
        cache_discovery=False
    )
    calendar = build(
        'calendar', 'v3',
        credentials=credentials,
        cache_discovery=False
    )
    return gmail, calendar

# Use both in one agent
creds = get_credentials()
gmail_service, calendar_service = build_google_services(creds)

# Test calendar access
cal_list = calendar_service.calendarList().list().execute()
for cal in cal_list.get('items', []):
    print(f'Calendar: {cal["summary"]}')

Google APIエラーの処理

Google APIのエラーはgoogleapiclient.errors.HttpErrorとして発生します。エラーにはHTTPステータスコードと、エラーの詳細を含むJSON本文が格納されています。デバッグできるよう、必ずこれを捕捉し、ステータスとメッセージをログに記録してください。

from googleapiclient.errors import HttpError
import json

def safe_gmail_call(service, user_id='me'):
    try:
        profile = service.users().getProfile(userId=user_id).execute()
        return profile
    except HttpError as e:
        status = e.resp.status
        try:
            error_body = json.loads(e.content.decode())
            message = error_body.get('error', {}).get('message', str(e))
        except Exception:
            message = str(e)

        if status == 401:
            print('AUTH ERROR: Credentials invalid or expired')
        elif status == 403:
            print(f'PERMISSION ERROR: {message}')
            print('Check scopes and domain-wide delegation settings')
        elif status == 429:
            print('QUOTA EXCEEDED: Gmail API rate limit hit')
        else:
            print(f'Gmail API error {status}: {message}')
        return None

Google APIのクォータとレート制限

Gmail APIには使用クォータがあります。デフォルトでは1日あたり10億クォータユニットで、各呼び出しのコストは操作に応じて1〜100ユニットです。メッセージの読み取りは一覧表示よりもコストが高くなります。制限内に収めるため、バッチリクエストを使用し、429/503エラーが発生した場合は指数バックオフを使用してください。

import time
from googleapiclient.errors import HttpError

def gmail_call_with_retry(func, max_retries=5):
    for attempt in range(max_retries):
        try:
            return func()
        except HttpError as e:
            if e.resp.status in (429, 500, 503):
                wait = (2 ** attempt) + 1
                print(f'Quota/server error. Waiting {wait}s (attempt {attempt+1})')
                time.sleep(wait)
            elif e.resp.status == 403:
                # Check if it's a quota exceeded vs permission error
                import json
                body = json.loads(e.content.decode())
                reason = body.get('error', {}).get('errors', [{}])[0].get('reason', '')
                if reason == 'rateLimitExceeded':
                    time.sleep(2 ** attempt)
                else:
                    raise  # real permission error, don't retry
            else:
                raise
    raise Exception(f'Gmail API call failed after {max_retries} attempts')

認証情報の安全な保存

token.json、credentials.json、service-account.jsonをバージョン管理システムに絶対にコミットしないでください。これらを.gitignoreに追加してください。本番環境では、サービスアカウントのJSONを環境変数またはシークレットマネージャーに保存し、実行時に読み込んでください。

import json
import os
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_credentials_from_env():
    # Load service account JSON from environment variable
    sa_json = os.environ.get('GOOGLE_SERVICE_ACCOUNT_JSON')
    if not sa_json:
        raise EnvironmentError(
            'GOOGLE_SERVICE_ACCOUNT_JSON env var not set. '
            'Set it to the contents of your service-account.json'
        )

    sa_info = json.loads(sa_json)
    credentials = service_account.Credentials.from_service_account_info(
        sa_info,
        scopes=SCOPES
    )
    return credentials

# In production: export GOOGLE_SERVICE_ACCOUNT_JSON=$(cat service-account.json)
creds = get_credentials_from_env()
print('Service account loaded from env var')

クイックチェック:サービスアカウントとユーザーOAuth

Gmail APIの認証方法についての理解度を確認しましょう。

Gmail API接続のまとめ

これで、エージェントをGmailに接続できるようになりました。

  • User OAuth:InstalledAppFlowを使用してtoken.jsonを保存し、次回以降の実行で自動更新する
  • Service Account:JSONキーを読み込み、委任のために.with_subject(user_email)を呼び出す
  • Scopes:必要最小限を要求する(gmail.readonly、gmail.send、calendar.events)
  • build('gmail', 'v1', credentials=creds)でサービスを構築する
  • APIエラーにはHttpErrorを捕捉し、429/503では再試行する
  • 認証情報ファイルは絶対にコミットせず、本番環境では環境変数を使用する

よくある質問

「API経由でGmailに接続する」レッスンは無料ですか?

はい。「API経由でGmailに接続する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「API経由でGmailに接続する」で何を学びますか?

Google APIクライアントライブラリ、OAuth2同意画面、Gmailスコープの選択を学びます。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「API経由でGmailに接続する」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. API経由でGmailに接続する
  2. プログラムによるメールの読み取りと送信
  3. カレンダーイベントの作成と検索
  4. シンプルなメールアシスタントエージェントの構築
← AI Agentsに戻る