Gmail APIを使ってみる

  • 公式ガイドにかいてあるとおりやってみる。以下適当に和訳。

Step 1: APIの有効化

  1. Google Developers Consoleでプロジェクトを作ると自動的にAPIが有効化になる。ウィザードどおり続けて認証情報を取得する。
  2. プロジェクトへの認証情報の追加ではキャンセルをクリックする。
  3. 上のタブから、OAuth同意画面を選択する。googleアカウントのメールアドレスと、任意のサービス名を入力して保存。
  4. 認証情報タブを選択 -> 認証情報の作成 -> OAuthID作成を選択
  5. 「その他のアプリケーション」を選択肢、名称は"Gmail API Quickstart"を入力して「作成」ボタン
  6. 表示されるクライアントIDとクライアントシークレットを一応保存
  7. 右端のダウンロードボタンをクリックしてclient_secret.jsonと名前をつけて保存

Step 2: Google クライアントライブラリのインストー

  • pipでインストールするだけ
$ pip install --upgrade google-api-python-client

Step 3: サンプルファイル作成

  • quickstart.pyというファイルをつくる。中身は公式どおり。

Step 4: 実行

$ python quickstart.py
  • 問題なく実行でき、自分のgmailアカウントのラベルが取得できた。
  • 一度認証するとspyderのなかでもできるようだ。便利

gmailを検索してみる

  • 公式pythonのサンプルコードがあるのでそれを実行するだけ

  • Google APIの証明書を取得

  • メールボックスを検索して特定の文字列に一致するメールのIDを取得
  • そのIDのメール本文を表示
# 証明書を取得する関数。以下すべて公式サンプルのコピペ

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

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
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: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


# 文字列を指定してメールを検索し、メッセージIDを返す関数。python3用に一部print文を書き換え日本語も使える。

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)


#メッセージIDを使ってメール本文を取得する関数
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を検索して特定の正規表現にマッチするものを抽出したい。