Pythonを使ってGmailの送受信を自動化したい場面は多くあります。例えば、定期レポートを送信したり、受信メールを自動で読み取って処理をしたりと、業務効率化に役立ちます。
この記事では、Googleが提供するGmail APIを使って、Pythonでメールを送信・取得する方法を解説します。OAuth2.0を使った認証の流れから、APIでメール本文を扱う方法までを順を追って紹介します。
Gmail APIを使うための準備
まずはGoogle Cloud Consoleでプロジェクトを作成し、Gmail APIを有効にします。
- Google Cloud Consoleにログイン
- 新しいプロジェクトを作成
- 「Gmail API」を有効化
- OAuth同意画面を設定
- OAuth2.0の「デスクトップアプリ」クライアントIDを作成
- クレデンシャル(credentials.json)をダウンロード
必要なライブラリのインストール
以下のコマンドで必要なPythonライブラリをインストールします。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
OAuth2.0を使った認証処理
初回アクセス時にはブラウザでGoogleアカウント認証が必要です。認証トークンはローカルに保存して再利用できます。
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
import os.path
import pickle
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def get_gmail_service():
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:
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)
メールの送信方法
Base64でエンコードしたMIME形式のメッセージを送信します。
import base64
from email.mime.text import MIMEText
def create_message(to, subject, body):
message = MIMEText(body)
message['to'] = to
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_email(service, to, subject, body):
message = create_message(to, subject, body)
service.users().messages().send(userId='me', body=message).execute()
# 使用例
service = get_gmail_service()
send_email(service, 'example@example.com', 'テスト件名', 'テスト本文')
メールの取得方法
特定の件名やラベルでメールを検索し、本文を取得できます。
def get_messages(service, query=''):
result = service.users().messages().list(userId='me', q=query).execute()
messages = result.get('messages', [])
return messages
def get_message_body(service, msg_id):
msg = service.users().messages().get(userId='me', id=msg_id, format='full').execute()
parts = msg['payload'].get('parts', [])
for part in parts:
if part['mimeType'] == 'text/plain':
data = part['body']['data']
return base64.urlsafe_b64decode(data).decode()
return ''
例:get_messages(service, 'subject:レポート')
で件名に「レポート」を含むメールを取得可能です。
まとめ
Gmail APIを使えば、Pythonで柔軟なメール処理が可能になります。OAuth認証のステップを踏むことで、安全に自動化でき、業務効率化にもつながります。
定期レポートの自動送信や、受信トレイの監視・ログ化など、さまざまな活用ができるため、ぜひ導入を検討してみてください。