前編では、pythonでGmailの設定する流れを確認しました。
参考 【python+poetry】GmailのAPIでメール内容を取得する流れ【前編】クリワンのPython日記今回は、実際に、スクリプトまでを書いていきます。
ファイルの構成
Google API Platformでダウンロードしたファイルのファイル名を(今回は)以下に変更します。
credentials.json
続いて、gmailのAPIを作成します。ファイル名は、gmail_api.py にしました。
class GmailAPI:
def __init__(self):
# If modifying these scopes, delete the file token.json.
self._SCOPES = "https://www.googleapis.com/auth/gmail.readonly"
def connect_gmail(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
flowの部分には、先のファイル名’credentials.json’ を引数に入れています。
poetryの設定
僕はpoetryを使っているので、gmailをaddしておきます。
poetry add gmail
以下でできました。
Using version ^0.6.3 for gmail
Updating dependencies
Resolving dependencies... (0.6s)
Writing lock file
Package operations: 1 install, 0 updates, 0 removals
- Installing gmail (0.6.3)
続いて、oauth2clientをaddします。
poetry add oauth2client
以下でできました。
Using version ^4.1.3 for oauth2client
Updating dependencies
Resolving dependencies... (0.4s)
Writing lock file
Package operations: 7 installs, 0 updates, 0 removals
- Installing pyasn1 (0.4.8)
- Installing pyparsing (2.4.7)
- Installing httplib2 (0.19.1)
- Installing pyasn1-modules (0.2.8)
- Installing rsa (4.7.2)
- Installing six (1.15.0)
- Installing oauth2client (4.1.3)
Gmailのセキュリティ環境
初めて処理をする際は、Googleのアカウントのセキュリティからのエラーが発生するため、
以下の処理が必要になります。
まず、Googleのアカウントから、セキュリティを選択します。

続いて、「安全性の低いアプリ」のアクセスを有効にします。

もしもGmailの二段階認証をしている方は、以下を参照してください。
参考 【Python】二段階認証設定しているgmailからメール送信QiitaPythonのスクリプトを作成
今回は、以下のスクリプトを作成しました。
ファイル名は、inbox.py にしました。

スクリプト内容
import imaplib
import email
from oauth2client.service_account import ServiceAccountCredentials
from email.message import EmailMessage
host = 'imap.gmail.com'
username = 'xxxxxxxxx@gmail.com'
password = 'xxxxxxxxxxxxx'
def get_inbox():
mail = imaplib.IMAP4_SSL(host)
mail.login(username, password)
mail.select('inbox')
_, search_data = mail.search(None, 'UNSEEN')
my_message = []
for num in search_data[0].split():
email_data = {}
_, data = mail.fetch(num, '(RFC822)')
# print(data[0])
_, b = data[0]
email_message = email.message_from_bytes(b)
#email_message = email.message_from_string(b)
for header in ['subject', 'to', 'from','date']:
print("{}:{}".format(header, email_message[header]))
email_data[header] = email_message[header]
# print(email_message)
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
email_data['body'] = body.decode()
elif part.get_content_type() == 'text/html':
html_body = part.get_payload(decode=True)
email_data['html_body'] = html_body.decode()
my_message.append(email_data)
return my_message
if __name__ == '__main__':
my_inbox = get_inbox()
print(my_inbox)
部分的な解説
usernameには、ご自身のメールアドレス、
passwordには、ご自身のパスワードが入ります。
host = 'imap.gmail.com'
username = 'xxxxxxxxx@gmail.com'
password = 'xxxxxxxxxxxxx'
今回は、inboxの中から、未読のメールを取得します。
ので、’UNSEEN’を選択しました。
def get_inbox():
mail = imaplib.IMAP4_SSL(host)
mail.login(username, password)
mail.select('inbox')
_, search_data = mail.search(None, 'UNSEEN')
my_message = []
実際にメールを取得
今回は、こちらの未読メールを取得します。

さっそく、poetryでpythonを実行します。
poetry run python inbox.py
以下で、実際に、メールの内容を取得することができました。
subject:Hello world
to:xxxxxxxx@gmail.com
from:=xxxxxxxxxxxxxxxx= <xxxxxxxx@gmail.com>
date:Thu, 1 Apr 2021 11:30:59 +0900
[{'subject': 'Hello world', 'to': 'xxxxxxxx@gmail.com', 'from': '=xxxxxxxxxxxxxxxx= <xxxxxxxx@gmail.com>', 'date': 'Thu, 1 Apr 2021 11:30:59 +0900', 'body': 'Hello xxxxxxxx,\r\nThank you for joining cfe.sh. We are very happy to have you with us.\r\n', 'html_body': '<div dir="ltr">Hello xxxxxxxx,<br>Thank you for joining cfe.sh. We are very happy to have you with us.<br></div>\r\n'}]
まとめ
前編・後編で、python+poetryでGmailとの連携までのフローを確認しました。
今回、ご紹介したスクリプトの内容は、
以下の動画を参考にしています。
とても勉強になるので、ぜひこちらもチェックしてみてください。
(ただ、残念ながら英語なので、ご注意ください!)