LoginSignup
17
25

More than 5 years have passed since last update.

Pythonを使ってGmail APIからメールを取得する

Posted at

Gmail APIを使ってメールを取得する方法をまとめました

概要

 この記事では、以下の内容を記載しています。
 ・Gmail API利用開始方法
 ・APIを使ったメールの取得

動作環境

 python3.7.0

Gmail APIを使うには

 Gmail APIを使うためには、事前に以下の作業が必要です。
 参考ページ:Python Quickstart |Gmail API

Step1 Gmail APIの有効化

 1.上記リンクのstep1より"Enable the Gmail API"ボタンをクリック
 2."+ Create a new project"を選択し、新規プロジェクトを作成(名前は何でも良い)
 3."DOWNLOAD CLIENT CONFIGURATION"をクリックして、"credentials.json"をダウンロード。"credentials.json"は、認証に使用します。

Step2 Google Client Libraryをインストールする

 pipを使って、Google Client Libraryをインストールします。
 pip install --upgrade google-api-python-client oauth2client

 これで準備は完了です。

メールの取得

 実際にAPIにアクセスして、日付と送信元アドレスでメールを検索します。
 実行すると、ヒットしたメールが一覧表示されます。
 ※初回実行時は、Gmailの認証が必要です。

GmailAPI.py
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

class GmailAPI:
    def __init__(self):
        # If modifying these scopes, delete the file token.json.
        self._SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'

    def ConnectGmail(self):
        store = file.Storage('token.json')
        creds = store.get()
        if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('credentials.json', self._SCOPES)
            creds = tools.run_flow(flow, store)
        service = build('gmail', 'v1', http=creds.authorize(Http()))

        return service

    def GetMessageList(self,DateFrom,DateTo,MessageFrom):

        #APIに接続
        service = self.ConnectGmail()

        MessageList = []

        query = ''
        # 検索用クエリを指定する
        if DateFrom != None and DateFrom !="":
            query += 'after:' + DateFrom + ' '
        if DateTo != None  and DateTo !="":
            query += 'before:' + DateTo + ' '
        if MessageFrom != None and MessageFrom !="":
            query += 'From:' + MessageFrom + ' '

        # メールIDの一覧を取得する(最大100件)
        messageIDlist = service.users().messages().list(userId='me',maxResults=100,q=query).execute()
        #該当するメールが存在しない場合は、処理中断
        if messageIDlist['resultSizeEstimate'] == 0: 
            print("Message is not found")
            return MessageList
        #メッセージIDを元に、メールの詳細情報を取得
        for message in messageIDlist['messages']:
            row = {}
            row['ID'] = message['id']
            MessageDetail = service.users().messages().get(userId='me',id=message['id']).execute()
            for header in MessageDetail['payload']['headers']:
                #日付、送信元、件名を取得する
                if header['name'] == 'Date':
                    row['Date'] = header['value'] 
                elif header['name'] == 'From':
                    row['From'] = header['value']
                elif header['name'] == 'Subject':
                    row['Subject'] = header['value']
            MessageList.append(row)
        return MessageList

if __name__ == '__main__':
    test = GmailAPI()
    #パラメータは、任意の値を指定する
    messages = test.GetMessageList(DateFrom='2018-01-01',DateTo='2018-02-01',MessageFrom='xxxxxxxxxxx@xxxxx.com')
    #結果を出力
    for message in messages:
        print(message)

おわりに

 今回はメールを取得して一覧を表示するだけでしたが、GmailAPIには他にも機能があるので色々応用できそうです。今後、他の使い方も考えていきたいと思います。
 

17
25
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
25