Gmail APIを使ってGmail関連の処理を自動化したいと思い、PythonでOAuth認証を試したのですが、ひっかかったので解決策を共有します。
こちらが本家の公式ガイド:Python Quickstart
https://developers.google.com/gmail/api/quickstart/python
こちらのサンプルコードですが、ローカル環境でやる分には問題ないのですが、WEBサーバーから認証かける際には、authorization codeを入力することが出来ないため問題となります。
具体的には以下の通り修正すればOKです。
【修正前】
・・・
# 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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
・・・
【修正後】
・・・
# 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(
'credentials.json', SCOPES,
redirect_uri='http://example.com')
# Tell the user to go to the authorization URL.
auth_url, _ = flow.authorization_url(prompt='consent')
print('Please go to this URL: {}'.format(auth_url))
# The user will get an authorization code. This code is used
to get the
# access token.
code = input('Enter the authorization code: ')
flow.fetch_token(code=code)
creds = flow.credentials
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
・・・
PHP Quickstartのサンプルコードだと、Enter the authorization code:が出てくるのにPythonだと出てこないなんて若干不親切だなと思った次第でした。
ちなみに、PHP版ですがこの人がめっちゃ親切に解説してくれてます。
Google Gmail API Ep. 1 – Quickstart
以上


