![見出し画像](https://assets.st-note.com/production/uploads/images/159829403/rectangle_large_type_2_fbb504d36c17ebe6cc9b25003d9f9156.png?width=1200)
[ソースコード有]2要素認証Gmailの突破方法
Googleが提供する Gmail API を使うと、自分のGmailアカウントから安全にメールを取得することができます。この方法はセキュリティとプライバシーを確保しながらも、メール内容を自動的に処理するのに便利です。この記事では、Gmail APIの設定方法とPythonを使ったコード例を紹介します。
例えば、物を購入する工程を自動化する際にgmail側にパスコードが送られたりすると思いますが、そういった2要素認証を突破する際に使用できます。
またGmailの内容を他アプリに通知したいなどにも使えますのでよければご参考にしてください。
画像を多く入れておりますので初心者でもわかるかと思います。
準備:Gmail APIを使うための設定
1Google Cloud Consoleでプロジェクトを作成
Google Cloud Console にアクセスし、新規プロジェクトを作成します。
https://console.cloud.google.com/
※Gmailを取得したいアカウントで上記URLをクリックしてください
![](https://assets.st-note.com/img/1730210817-aWNnM632ohQm04us9EqeXKGJ.png?width=1200)
![](https://assets.st-note.com/img/1730210834-J29IhHxCn1EpiRMqusok8L6P.png?width=1200)
![](https://assets.st-note.com/img/1730210878-aQnVZ7Fl5Bp8ymHo4dwg9WDN.png?width=1200)
project name/location はなんでもよいです
![](https://assets.st-note.com/img/1730210972-J9iqTC8gfoPaM5yYrKnlkLbm.png?width=1200)
2 Gmail APIを有効化
作成したプロジェクトの「APIとサービス」から「ライブラリ」を選択し、「Gmail API」を検索して有効にします。
![](https://assets.st-note.com/img/1730211130-bLSW6ZBXroAvC0hK5HD31x28.png?width=1200)
![](https://assets.st-note.com/img/1730211209-ScmGyF5bXTv0pWC38nB1hAlE.png?width=1200)
![](https://assets.st-note.com/img/1730211241-YJBTto10lCxWrpuvbDHViFdk.png?width=1200)
3 OAuth 2.0 クライアントIDを作成
「認証情報」から「+ 認証情報を作成」ボタンを押し、「OAuth クライアントID」を選択します。
![](https://assets.st-note.com/img/1730211489-JIvKrSYX76pGuoykRMP1mh2d.png?width=1200)
![](https://assets.st-note.com/img/1730211514-JF1HVUcuQ9z5v6LapbfxmiPA.png?width=1200)
![](https://assets.st-note.com/img/1730211543-2KICVJZHxrpjmLo4FYdg9NaS.png?width=1200)
![](https://assets.st-note.com/img/1730211594-RAhiljkFLNqam1tcu2IDMS53.png?width=1200)
![](https://assets.st-note.com/img/1730211770-1mERWJGvsM5Zc3liBHxoCdt9.png?width=1200)
違いとしては以下になります。ここではexternalを選択。
Internal: 組織内のみ利用、承認不要。
External: 組織外も対象、テスト段階でのユーザー制限、必要に応じてGoogleの承認が必要。
詳細は以下になります。
![](https://assets.st-note.com/img/1730212223-tHXK5E10CqPS3YsZyMJ7r46c.png?width=1200)
![](https://assets.st-note.com/img/1730212453-JaGd0CO2k56gXy1pS4TwPuFH.png?width=1200)
App name はなんでもよいです。
User support email はよく使うemailアドレスを指定すればよいです。
とりあえずここでは、gmailを使っております。
![](https://assets.st-note.com/img/1730212643-odqVDA7inQEGaNhR6UkczPrg.png?width=1200)
同様にdeveloper contact information 用のEmail addresses を記載して
SAVE AND CONTINUEを押してください
![](https://assets.st-note.com/img/1730212879-XtVPbY9xZmOvDhjrpIK1F4ag.png?width=1200)
![](https://assets.st-note.com/img/1730213008-fyFWjJqB1SaT0nDIdK9cE3V5.png?width=1200)
その後SAVE AND CONTINUE をクリック
![](https://assets.st-note.com/img/1730213165-zBmYhf4ARHl3sWD2irNdbGJX.png?width=1200)
4 アプリケーションの種類に「デスクトップアプリ」を選択し、必要な情報を入力して「作成」します。
![](https://assets.st-note.com/img/1730213414-OYjiq3EAtclV5an9L1fBrdKG.png?width=1200)
Credentials-CREATE CREDENTIALS -OAuth client ID を順にクリックする。
![](https://assets.st-note.com/img/1730213645-r6Lxm305Vg2sJ9RzTI1jwUeP.png?width=1200)
![](https://assets.st-note.com/img/1730213697-vyktaJX3OhBPMbsmuCnZifcK.png?width=1200)
Name はなんでもよいです。
5 クレデンシャルファイルをダウンロード
作成したクライアントIDの「ダウンロード」ボタンをクリックし、credentials.jsonという名前で保存します。このファイルをプログラムと同じフォルダに配置します。
![](https://assets.st-note.com/img/1730213929-vYnKAJaS2uFIZ7BhtRs9kGH1.png?width=1200)
上述のとおりダウンロードしたファイルのjsonファイルの名前を
credentials.json としておいてください。
ここまででAPIのクライアントシークレットキーが取得できました。
ここからこのキーを使ってpythonコードでGMAILを取得していきます。
6 サンプルコードの実行
サンプルコード:Gmail APIを使ってメールを取得
以下のコードは、Gmail APIを使って自分のメールを取得し、メールの件名と本文の一部を表示するPythonのサンプルです。
import os
import base64
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Gmail API scope (read-only access)
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def gmail_authenticate():
"""Authenticates with Gmail API and retrieves credentials.
Returns:
Credentials object for authorized access.
"""
creds = None
if os.path.exists('token.json'):
# Load credentials from existing token file
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
else:
# Initiate authorization flow if token file doesn't exist
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save credentials for future use
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def get_messages(service, user_id='me'):
"""Retrieves and prints a summary of messages from the specified user's inbox.
Args:
service: Gmail API service object.
user_id (str, optional): User's email address (defaults to 'me').
"""
results = service.users().messages().list(userId=user_id).execute()
messages = results.get('messages', [])
for msg in messages:
# Get message details and subject
txt = service.users().messages().get(userId=user_id, id=msg['id']).execute()
payload = txt['payload']
headers = payload['headers']
for d in headers:
if d['name'] == 'Subject':
subject = d['value']
print(f"Subject: {subject}")
# Check for plain text parts and print the first 100 characters
if 'parts' in payload:
parts = payload['parts']
for part in parts:
if part['mimeType'] == 'text/plain':
data = part['body']['data']
text = base64.urlsafe_b64decode(data).decode("utf-8")
print(f"Message: {text[:100]}")
print("="*50) # Print a separator between messages
def main():
"""Main function to perform authentication and message retrieval."""
creds = gmail_authenticate()
service = build('gmail', 'v1', credentials=creds)
get_messages(service)
if __name__ == '__main__':
main()
コードの説明
gmail_authenticate関数
credentials.json を使って認証を行い、token.json に認証情報を保存します。このファイルがあると、再度の認証を省略できます。
get_messages関数
メールのリストを取得し、各メールの件名(Subject)と本文の一部を表示します。本文はtext/plainの内容を取得し、デコードして表示しています。
main関数
認証とGmail APIサービスの作成を行い、メールを取得する関数を呼び出します。
初回実行時は以下のようなアカウントの選択画面が出ると思います。
![](https://assets.st-note.com/img/1730215174-oJOwKX3A5rLn4yx69cPEHhSU.png?width=1200)
適切なアカウントではない場合以下のようなエラーとなります。
ここでいう適切とはADD USERS で追加したアカウントを指します。
![](https://assets.st-note.com/img/1730215275-XDxqWofymB3R6aZrI18vnFbi.png?width=1200)
良い場合は以下のような画面になります。
![](https://assets.st-note.com/img/1730215368-rAelQ7kWyvCpo9ZN02bu6waM.png?width=1200)
続行をクリックしてください。
![](https://assets.st-note.com/img/1730215412-IsxK0ytFzDecjgvum52NYLfw.png?width=1200)
これでpythonコードのターミナル画面でメールが取得できていると思います。
2回目以降はtoken.jsonファイルをもとにアクセスします。
一定期間アクセスがない場合はjsonファイルの作り直しになります。
参考になった方はいいねいただけると嬉しいです。