FANCOMI Ad-Tech Blog

株式会社ファンコミュニケーションズ nend・新規事業のエンジニア・技術ブログ

Gmail API取得できたけど、OAuth認証でひっかかった話

こんにちは。ファンコミュニケーションズのr_nakayamaです。
初ブログです!

今日のBlogは、
『 社内メールで利用しているGmail、
  そのうちプログラマティックに使うだろうし、下準備でもしておこうかしら。』
ということで、Gmailをスクリプトから送信してみた話です。

Gmail APIを使った記事は他にもたくさんありますが、
認証コードの取得に関して詳しくまとめているつもりなので、
『 認証コード取得できないんですけど!』
という方にぜひ読んでいただければと思います。

【目次】

参考にしたページはこちら。
http://thinkami.hatenablog.com/entry/2016/06/10/065731

Gmail API の取得

まず、Gmail APIを取得しないといけないのですが、参考ページそのままなので割愛m(_ _)m

認証コードの取得

で、Gmail APIを取得して保存しましたら、端末の認証を受けないといけません。

SCOPES = "https://www.googleapis.com/auth/gmail.send"

def get_credentials():
    script_dir =os.path.abspath(os.path.dirname(__file__)) 
    credential_dir = os.path.join(script_dir, ".credentials")

    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "my-gmail-sender.json")

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = oauth2client.tools.run_flow(flow, store, flags)
        print("Storing credentials to " + credential_path)
    return credentials

これを実行すると、認証の画面が開きます。。。

(認証画面)
f:id:fan_r_nakayama:20171201170619p:plain
おお。。。w3mの使い方はこちら。。。
http://johnen.shinshu-u.ac.jp/~matsu/lectures/cl/w3m-key-bindings.html


ただし!ここで、すんなり認証していただければいいのですが、
さすが(?)、会社ネットワーク、、、すんなり認証してくれない。。。

原因としてまず考えられたのが、
Cloud Gateをセキュリティーとして導入しているので、
まず、ここを突破しないといけない??(ここは原因ではありませんでした。。。)

勘違いした私は、seleniumを使って、Cloud Gateの認証画面から端末登録をして、
driverに登録端末のcookieをわたして
ログインしようとかいろいろやってみたりもしました。。。

二つ目に原因として考えられたのが、
仮想サーバーからアクセスしているために、
何かしら問題があったのではないかということです。

とまあ、原因はいろいろ考えられますが、、、

--noauth_local_webserver オプション

>python gmail_sender.py
Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?access_type=offline...

If your browser is on a different machine then exit and re-run this application with the command-line parameter

  --noauth_local_webserver

よく見ると、実行時に上のお知らせがあったので、
--noauth_local_webserver オプションをつけて再実行してみると、、、

>python3 gmail_sender.py --noauth_local_webserver
/usr/local/lib/python3.5/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access /home/(path)/gmail_api/.credentials/my-gmail-sender.json: No such file or directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?client_id=~~~

Enter verification code: [ここで認証コードをinputする]

あなたのブラウザからこのURLにアクセスしてください、と言われたので、アクセスすると、

(アカウント選択画面)
f:id:fan_r_nakayama:20171201104413p:plain

(許可する)
f:id:fan_r_nakayama:20171201104425p:plain

(認証コードゲット!!!)
f:id:fan_r_nakayama:20171201113951p:plain
さきほどの実行画面に認証コードをinputしてEnter!!!

Enter verification code: ●●●●●●●●●●●●●●●
Authentication successful.
Storing credentials to /home/(path)/gmail_api/.credentials/my-gmail-sender.json

これで仮想端末からGmailにアクセスできるようになりました!

gmail_sender の実行

あとは参考ページにあるgmail_sender.pyを実行してください。
https://github.com/thinkAmi-sandbox/google-api-python-client-sample

(送信結果)
f:id:fan_r_nakayama:20171201110121p:plain
無事メッセージを送ることができました!

プログラマティックにGmailを使う話はまた後日〜!

最後に

弊社では随時インターン生を募集しています。詳細は下のページを見てください!

www.wantedly.com