Django で Gmail を送信する

次の記事との違いは、
[Django でメールを送信する](https://qiita.com/ekzemplaro/items/4ab21be0ea8130c2b59b)
メールサーバーを Gmail として、oauth2 を使うことです。

A) プロジェクト　proj01
   アプリ　gmail_send
   を用意。

B) 自作のモジュールを mail_send/lib/ に入れます。

```text
lib
├── credentials.json
├── gmail_send.py
└── test_gmail.py
```

>credentials.json は取得したものです。

```py:gmail_send/lib/gmail_send.py
#! /usr/bin/python
#
#	gmail_send.py
#
#					Dec/28/2018
# ------------------------------------------------------------------
import httplib2
import os
import sys

import apiclient
import oauth2client
import argparse
from oauth2client import file, client, tools
# ------------------------------------------------------------------
import base64
from email.mime.text import MIMEText
from email.utils import formatdate
import traceback

SCOPES = "https://www.googleapis.com/auth/gmail.send"
CLIENT_SECRET_FILE = "credentials.json"
APPLICATION_NAME = "MyGmailSender"

# ------------------------------------------------------------------
# [6-4]:
def get_credentials(flags):
	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
#
# ------------------------------------------------------------------
# [6-8]:
def create_message(mail_from,mail_to,subject,str_message):
	message = MIMEText(str_message)
#
	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")

	return {"raw": str_msg_b64encoded}
#
# ------------------------------------------------------------------
# [6]:
def gmail_send_proc(mail_from,mail_to,subject,str_message,flags):
	credentials = get_credentials(flags)
	http = credentials.authorize(httplib2.Http())
	service = apiclient.discovery.build("gmail", "v1", http=http)
#
	try:
		result = service.users().messages().send(
			userId=mail_from,
			body=create_message(mail_from,mail_to,subject,str_message)
		).execute()

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

	except apiclient.errors.HttpError:
		print("------start trace------")
		traceback.print_exc()
		print("------end trace------")
#
# ------------------------------------------------------------------
```

>次の mail_from と mail_to　は変更して下さい。

```py:gmail_send/lib/test_gmail.py
#! /usr/bin/python
#
#	test_gmail.py
#
#					Dec/28/2018
# ------------------------------------------------------------------
import sys

import argparse
import oauth2client

from gmail_send import gmail_send_proc 

flags = argparse.ArgumentParser(
    parents=[oauth2client.tools.argparser]
).parse_args()

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
mail_from = "aaabbb@gmail.com"
mail_to = "cccc@example.com"
#
subject = "Gmail Api Test Dec/28/2018 PM 18:46"
str_message = ""
str_message += "おはよう\n"
str_message += "晴れています。\n"
str_message += "Dec/28/2018 PM 18:46\n"
#
print(flags)
#
gmail_send_proc(mail_from,mail_to,subject,str_message,flags)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
```

c) .credentials の取得

```bash
./test_gmail.py --noauth_local_webserver
```

>スクリプトの指示に従って、コードを入れて下さい。

d) gmail_send/view.py の編集
>mail_from と mail_to　は変更して下さい。

```py:gmail_send/view.py
# ------------------------------------------------------------------
import sys
from django.http import HttpResponse

from gmail_send.lib.gmail_send import gmail_send_proc 
# ------------------------------------------------------------------

def index(request):
	sys.stderr.write("*** aaa ***\n")
	gmail_main_proc()
	sys.stderr.write("*** ccc ***\n")
	str_out = "Good Afternoon<p />"
	str_out += "こんにちは<p />"
	return HttpResponse(str_out)

# ------------------------------------------------------------------
def gmail_main_proc():
	sys.stderr.write("*** 開始 ***\n")
	flags = None
#
	mail_from = "aaabbb@gmail.com"
	mail_to = "ccc@example.com"
#
	subject = "Gmail Api Test Dec/28/2018 PM 18:56"
	str_message = ""
	str_message += "おはよう\n"
	str_message += "晴れています。\n"
	str_message += "Dec/28/2018 PM 18:56\n"
#
	gmail_send_proc(mail_from,mail_to,subject,str_message,flags)
#
	sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
```

D) 開発サーバーを起動

```bash
python manage.py runserver
```

E) ブラウザーで http://127.0.0.1:8000/gmail_send/ にアクセス

>すぐにメールが送られます。