- 公式ガイドにかいてあるとおりやってみる。以下適当に和訳。
Step 1: APIの有効化
- Google Developers Consoleでプロジェクトを作ると自動的にAPIが有効化になる。ウィザードどおり続けて認証情報を取得する。
- プロジェクトへの認証情報の追加ではキャンセルをクリックする。
- 上のタブから、OAuth同意画面を選択する。googleアカウントのメールアドレスと、任意のサービス名を入力して保存。
- 認証情報タブを選択 -> 認証情報の作成 -> OAuthID作成を選択
- 「その他のアプリケーション」を選択肢、名称は"Gmail API Quickstart"を入力して「作成」ボタン
- 表示されるクライアントIDとクライアントシークレットを一応保存
- 右端のダウンロードボタンをクリックしてclient_secret.jsonと名前をつけて保存
Step 2: Google クライアントライブラリのインストール
$ pip install --upgrade google-api-python-client
Step 3: サンプルファイル作成
- quickstart.pyというファイルをつくる。中身は公式どおり。
Step 4: 実行
- quickstart.pyとclient_secret.jsonを同じディレクトリにおいて実行。
$ python quickstart.py
- 問題なく実行でき、自分のgmailアカウントのラベルが取得できた。
- 一度認証するとspyderのなかでもできるようだ。便利
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else:
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: String used to filter messages returned.
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
Returns:
List of Messages that match the criteria of the query. Note that the
returned list contains Message IDs, you must use get with the
appropriate ID to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
q=query).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, q=query,
pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError as error:
print('An error occurred: %s' % error)
import base64
import email
from apiclient import errors
def GetMessage(service, user_id, msg_id):
"""Get a Message with given ID.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
print('Message snippet: %s' % message['snippet'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
やりたいこと:gmailを検索して特定の正規表現にマッチするものを抽出したい。