Bluemix と Heroku の Flask で、Gmail の oauth 2.0 を使う

関連ページ　次のページのコードを使っています。
Flask 関連
[Bluemix で、Node-RED で作成した API を、Flask から呼び出す](http://qiita.com/ekzemplaro/items/1c05d13a3b4aaa10224a)

* static/index.html
* static/mail.js

Gmail oauth 2.0 関連
[Python で、Gmail の oauth 2.0 を使う](http://qiita.com/ekzemplaro/items/8777d0bde5675af82d16)

* get_credentials.py
* client_secret.json
* .credentials/my-gmail-sender.json

フォルダー構成
>Heroku では manifest.yml は不要です。

```text
├── client_secret.json
├── get_credentials.py
├── Procfile
├── requirements.txt
├── runtime.txt
├── send_gmail_oauth2.py
├── static
│   ├── index.html
│   ├── lib
│   │   └── jquery-3.3.1.min.js
│   └── mail.js
├── welcome.py
├── manifest.yml
└── .credentials/my-gmail-sender.json
```

```py3:welcome.py
# -*- coding: utf-8 -*-
#
#	welcome.py
#
#						Aug/30/2017
#
# ----------------------------------------------------------------------
import sys
import os

from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)

from send_gmail_oauth2 import send_gmail_proc
# ----------------------------------------------------------------------
@app.route("/")
def welcome():
	print("welcome")
	return app.send_static_file('index.html')
# ----------------------------------------------------------------------
@app.route('/post_mail' ,methods=['POST'])
def mail_proc():
	print("*** post_mail *** start ***")
	message = []
	message.append("*** mail *** start ***")
	message.append("request.method = " + request.method)
#
	to = request.form['to']
	topic = request.form['topic']
	content = request.form['content']
#
	try:
		send_gmail_proc(to,topic,content)
	except Exception as ee:
		sys.stderr.write("*** error *** send_gmail_proc ***\n")
		message.append("*** error *** send_gmail_proc ***")
		sys.stderr.write(str(ee) + "\n")
		message.append(str(ee))
#
	message.append("*** mail *** end ***")
	print("*** mail *** end ***")
#
	rvalue={}
	rvalue['to'] = to
	rvalue['content'] = content
	rvalue['message'] = message
#
	return jsonify(rvalue)
# ----------------------------------------------------------------------
port = os.getenv('PORT', '5000')
if __name__ == '__main__':
	app.debug = True
	app.run(host='0.0.0.0',  port=int(port))
# ----------------------------------------------------------------------
```

```py3:send_gmail_oauth2.py
# -*- coding: utf-8 -*-
#
#	send_gmail_oauth2.py
#
#					Aug/30/2017
# ------------------------------------------------------------------
import httplib2
import os
import sys
import apiclient
import base64
import traceback
from email.mime.text import MIMEText
from email.utils import formatdate

from get_credentials import get_credentials
# ------------------------------------------------------------------
def send_gmail_proc(to,topic,content):
#
	credentials = get_credentials()
	http = credentials.authorize(httplib2.Http())
	service = apiclient.discovery.build("gmail", "v1", http=http)

	mail_from = "test_aa@gmail.com"

	try:
		result = service.users().messages().send(
			userId=mail_from,
			body=create_message(mail_from,to,topic,content)
		).execute()

		print("Message Id: {}".format(result["id"]))

	except apiclient.errors.HttpError:
		print("------start trace------")
		traceback.print_exc()
		print("------end trace------")
#
# ------------------------------------------------------------------
def create_message(mail_from,mail_to,subject,contents):
	message = MIMEText(contents)
#
	message["from"] = mail_from
	message["to"] = mail_to
	message["subject"] = subject
	message["Date"] = formatdate(localtime=True)

	byte_msg = message.as_string().encode(encoding="UTF-8")
	byte_msg_b64encoded = base64.urlsafe_b64encode(byte_msg)
	str_msg_b64encoded = byte_msg_b64encoded.decode(encoding="UTF-8")

	body = {"raw": str_msg_b64encoded}
#
	return body
#
# ------------------------------------------------------------------
```

```text:requirements.txt
Flask==1.0.2
requests==2.20.1
httplib2==0.12.0
oauth2client==4.1.3
google-api-python-client==1.7.4
```

```text:runtime.txt
python-3.7.1
```

```text:Procfile
web: python welcome.py
```