ウェブノウハウ

WEB KNOWHOW

Gmail APIでGmailの受信メールを一括取得&CSV化【Python】

3. Google APIのPythonライブラリのインストールと定義

前項までで準備は終わりました。
次は必要なライブラリをインストールします。

Google APIのPythonライブラリをインストール

今回の機能の実行に必要なGoogle APIのPythonライブラリをインストールします。
Windowsならコマンドプロンプト、Macならターミナルを起動して以下のコマンドを叩きます。

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

ライブラリのインストールが終わったら、

jupyter lab

でJupyterLabを起動します。

JupyterLabが起動したら、新しいNotebookを開きます。起動したNotebookには好きな名前を付けておきましょう。

 
※ ここから先はこのNotebook上にコードを書いて実行していきます。

ライブラリと認証情報ファイルの定義

ライブラリの定義

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from apiclient import errors
import base64
import csv
import email
import dateutil.parser

 
Gmail APIの認証情報ファイルの定義

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

# token.jsonを定義(実体ファイルは最初はなくてもOK。なければ作る処理を書くので)
tokenPath = "token.json"

# 認証情報ファイルを定義
credentialsPath = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com.json"
# ここにはダウンロードした認証情報ファイル名を記述します。
# 同じディレクトリにあるファイルならファイル名だけでOK

※ 認証ファイルについては「Gmail APIを登録する」に記載しておりますので、まだお読みでない方は読んできてください。
 

Gmail API初期化の関数と実行

Gmail APIとの接続の初期化をする関数

def gmail_init():
    creds = None
    # The file token.json 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(tokenPath):
        creds = Credentials.from_authorized_user_file(tokenPath, SCOPES)
    # 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:
            flow = InstalledAppFlow.from_client_secrets_file(
               credentialsPath, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(tokenPath, 'w') as token:
            token.write(creds.to_json())

    service = build('gmail', 'v1', credentials=creds)
    return service

 
と、ここまで書いたらAPI接続準備は終わりです。実行しましょう。
Gmail APIの初期化実行

service = gmail_init()

エラーが出なければGmail APIと接続完了。
 
さあ、これ以降は、Gmail APIからメールの情報を取得するための各機能を作っていきます。
お楽しみに。

【100ウェブ新着情報メルマガ】

WordPressカスタマイズ事例やウェブ制作ノウハウの新着情報、お役立ち情報を
リアルタイムにメルマガ配信!