昔 BASIC言語はやったことがあるので 似たようなインタープリタ言語 Python/パイソンにしました。なるべく段取りを簡単にしたいので、Googleのアカウントからログインできる Google Colab(Python)にしました。なんだか Googleの術中に嵌っているようですが、
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.')
でプログラムを書いた(生成?)のは初めてですが、コメントもちゃんと書いてあってプロっぽいのには驚きました。また、内容によって色分けされているので見易くなっています。
それでは次回 お楽しみに...