翻訳/Translate

2026年9月2日水曜日

260902 Google Colab(インタープリタ言語 Python/パイソン)で Gmailを読込むプログラムをAI生成

こんにちはHousukeです。



最近 PC界隈が AI一色になってしまいました。ところが 肝心のPCは 値段もなにもかも 行方が分からなくなっていて、得意にしている PC改造ネタのブログを書きにくくなりました。
そこで、プログラム作成とAIの合わせネタをやってみることにしました。
昔 BASIC言語はやったことがあるので 似たようなインタープリタ言語 Python/パイソンにしました。なるべく段取りを簡単にしたいので、Googleのアカウントからログインできる Google Colab(Python)にしました。なんだか Googleの術中に嵌っているようですが、AIも自動的に Geminiになりました。


🐲Google Colab(Python)によるプログラム作成🐲
溜まってしまったGmailを整理するために、一旦 それを全部読取るプログラムを お題にしました。
≣プログラム生成をGeminiに指示≣
Gmailを読み込むプログラム”と指示しました。


Geminiが生成した Pythonプログラム≣
指示から 10数秒後、次のように結果が出ました。

プログラム文を取り出してみました。
-------------------------------------------
import os
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_gmail_service():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens,
    # and is created automatically when the authorization flow completes for the first time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # Download your credentials.json file from Google Cloud Console
            # and upload it to your Colab environment.
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)
    return service

def list_messages(service, user_id='me'):
    try:
        response = service.users().messages().list(userId=user_id).execute()
        messages = []
        if 'messages' in response:
            messages.extend(response['messages'])

        while 'nextPageToken' in response:
            page_token = response['nextPageToken']
            response = service.users().messages().list(userId=user_id, pageToken=page_token).execute()
            messages.extend(response['messages'])
        return messages
    except Exception as e:
        print(f'An error occurred: {e}')
        return []

if __name__ == '__main__':
    # First, install the required libraries if you haven't already:
    # !pip install google-api-python-client google-auth-oauthlib

    # Get the Gmail service
    service = get_gmail_service()

    # List the first 10 messages (you can adjust the number or query)
    print('Listing messages...')
    messages = list_messages(service)

    if messages:
        print(f'Found {len(messages)} messages. Displaying first 10 IDs:')
        for i, message in enumerate(messages[:10]):
            print(f"Message ID: {message['id']}")

            # To get full message details, you would need to fetch each message:
            # msg = service.users().messages().get(userId='me', id=message['id']).execute()
            # print(f"Subject: {msg['payload']['headers'][...]['value']}") # This requires parsing headers

    else:
        print('No messages found.')
-------------------------------------------

AIでプログラムを書いた(生成?)のは初めてですが、コメントもちゃんと書いてあってプロっぽいのには驚きました。また、内容によって色分けされているので見易くなっています。
よく見ると なんか抜けてるような気がしないでもありませんが、次回 実行して問題があれば 修正した内容を お伝えしたいと思います。

それでは次回 お楽しみに...

0 件のコメント: