(更新: 2026.04.08)

複数Googleアカウント統合管理:1つのスクリプトで全アカウントを監視

はじめに

仕事で複数のGoogleアカウントを使い分けていると、それぞれのGmail・カレンダー・タスクを個別に確認するのは非効率です。この記事では、1つのPythonスクリプトで複数アカウントを統合管理する実装を紹介します。

課題

私の場合、以下の2つのアカウントを併用しています:

  • クロスリンク: work@example.com(60%)
  • プログラミングスクール: school@example.com(40%)

それぞれのGmailを個別にチェックすると、重要メールの見落としや対応漏れが発生します。

解決策:統合監視システム

アカウント設定の構造化

複数アカウントの認証情報をJSON形式で管理します。

{
  "accounts": [
    {
      "name": "crosslink",
      "email": "work@example.com",
      "token_path": "token_crosslink.json",
      "credentials_path": "credentials.json"
    },
    {
      "name": "programming_school",
      "email": "school@example.com",
      "token_path": "token_programming.json",
      "credentials_path": "credentials.json"
    }
  ]
}

統合チェックループ

各アカウントを順番にチェックし、結果を統合します。

import json

def check_all_accounts(config_path):
    with open(config_path) as f:
        config = json.load(f)

    all_important_emails = []

    for account in config['accounts']:
        print(f"🔍 Checking {account['name']}...")

        service = authenticate_gmail(
            account['token_path'],
            account['credentials_path']
        )

        emails = fetch_recent_emails(service, max_results=50)
        important = filter_important_emails(emails, account['name'])

        all_important_emails.extend(important)

    return all_important_emails

アカウント識別

検出したメールにアカウント情報をタグ付けします。

def filter_important_emails(emails, account_name):
    important = []

    for email in emails:
        score = calculate_importance_score(email)

        if score >= 35:  # Medium以上
            email['account'] = account_name
            email['score'] = score
            important.append(email)

    return important

通知の最適化

アカウント別の優先度

アカウントごとに異なる閾値を設定できます。

ACCOUNT_THRESHOLDS = {
    'crosslink': 35,  # Medium以上
    'programming_school': 50  # High以上
}

def should_notify(email, account_name):
    threshold = ACCOUNT_THRESHOLDS.get(account_name, 35)
    return email['score'] >= threshold

統合レポート

複数アカウントの結果を1つのレポートにまとめます。

def generate_report(important_emails, silent=False):
    if not important_emails:
        if not silent:
            print("✅ 重要メールなし")
        return

    # アカウント別にグループ化
    by_account = {}
    for email in important_emails:
        account = email['account']
        if account not in by_account:
            by_account[account] = []
        by_account[account].append(email)

    # レポート出力
    for account, emails in by_account.items():
        print(f"\n📧 {account.upper()} ({len(emails)}件)")
        for email in emails:
            print(f"  [{email['priority']}] {email['subject']}")

実運用での工夫

独立したトークン管理

各アカウントのOAuth2トークンを別ファイルで管理し、認証状態を独立させます。

gmail-watcher/
├── config.json
├── credentials.json
├── token_crosslink.json
└── token_programming.json

エラーハンドリング

1つのアカウントで認証エラーが発生しても、他のアカウントのチェックは継続します。

def check_all_accounts_safe(config_path):
    all_important = []

    for account in config['accounts']:
        try:
            emails = check_account(account)
            all_important.extend(emails)
        except Exception as e:
            print(f"⚠️ {account['name']} でエラー: {e}")
            continue  # 他のアカウントは継続

    return all_important

結果

2アカウント合計100通以上のメールから、10通の重要メールを抽出。アカウントごとのチェック漏れがなくなり、対応速度が向上しました。

まとめ

複数Googleアカウントを1つのスクリプトで統合管理することで、効率的なメール監視が実現できます。次はGoogle CalendarやTasksも統合し、完全なワークスペース管理を目指します。

関連記事:
– Gmail重要メール監視システム構築
– SQLiteでメール重複防止
– AI駆動タスク自動振り分け