PythonでGmailの添付ファイルを自動ダウンロード&フォルダ整理するスクリプト

はじめに

毎日届くメールの添付ファイルを手動で保存していませんか?
特に請求書やレポートなどの定期的な添付資料は、自動でダウンロード・整理できれば業務効率が大幅にアップします。

この記事では Python × Gmail API を使って、Gmailに届いた添付ファイルを自動でダウンロードし、指定したフォルダに振り分けるスクリプトを解説します。


必要な準備

1. Python環境

  • Python 3.8 以上
  • ライブラリ: google-api-python-client, google-auth, google-auth-oauthlib

インストールコマンド

pip install --upgrade google-api-python-client google-auth google-auth-oauthlib

2. Gmail API の有効化

  1. Google Cloud Console にアクセス
  2. プロジェクトを作成
  3. 「APIとサービス」→「ライブラリ」から Gmail API を有効化
  4. 「認証情報」→「OAuthクライアントID」を作成
  5. credentials.json をダウンロードして、スクリプトと同じフォルダに配置

サンプルスクリプト

以下のスクリプトでは、指定したラベルのメールから添付ファイルを取得し、拡張子ごとにフォルダ整理します。

from __future__ import print_function
import os
import base64
import email
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle

# Gmail APIのスコープ(読み取り専用)
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def gmail_authenticate():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

def save_attachment(service, user_id='me', query='has:attachment'):
    results = service.users().messages().list(userId=user_id, q=query).execute()
    messages = results.get('messages', [])

    if not messages:
        print("添付ファイル付きメールは見つかりませんでした。")
        return

    for msg in messages:
        msg = service.users().messages().get(userId=user_id, id=msg['id']).execute()
        for part in msg['payload'].get('parts', []):
            if part['filename']:
                data = part['body'].get('data')
                if not data:
                    att_id = part['body']['attachmentId']
                    att = service.users().messages().attachments().get(userId=user_id, messageId=msg['id'], id=att_id).execute()
                    data = att['data']
                file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))

                # 保存先フォルダを拡張子ごとに振り分け
                ext = os.path.splitext(part['filename'])[1].lower()
                folder = f"downloads/{ext[1:]}" if ext else "downloads/others"
                os.makedirs(folder, exist_ok=True)

                filepath = os.path.join(folder, part['filename'])
                with open(filepath, 'wb') as f:
                    f.write(file_data)
                print(f"保存完了: {filepath}")

if __name__ == '__main__':
    service = gmail_authenticate()
    save_attachment(service)

スクリプトのポイント

  • 認証情報の保存
    初回実行時にブラウザでGoogleアカウントにログインすると、token.pickle にトークンが保存され、次回以降は自動ログインできます。
  • 検索クエリの活用
    query='has:attachment' を変更することで、特定の送信者や件名に絞れます。
    例:
    • from:example@domain.com has:attachment
    • subject:請求書 newer_than:7d
  • フォルダ整理
    添付ファイルを拡張子ごとに自動仕分けすることで、
    • downloads/pdf/
    • downloads/xlsx/
    • downloads/others/
      のように分類可能。

実務での応用例

  • 毎月の 請求書を自動保存 → 会計フォルダに分類
  • チームメンバーから送られる 日報PDFを自動収集
  • 特定の顧客からの 契約書類を自動バックアップ

まとめ

Python × Gmail API を使えば、添付ファイルのダウンロード・整理を完全自動化できます。
特にルーティン作業の削減に直結するため、業務効率化の第一歩としておすすめです。

タイトルとURLをコピーしました