Django でメールを送信する

Django で yahoo のメールサーバーを使ってメールを送信するサンプルです。

A) プロジェクト　proj01
   アプリ　mail_send
   を用意。
   http://127.0.0.1:8000/mail_send/ にアクセスしてメッセージが出るようにします。

```bash
django-admin startproject proj01
cd proj01
python manage.py startapp mail_send
python manage.py migrate
```

>proj01/settings.py の編集
>proj01/urls.py の編集
>mail_send/urls.py の作成
>mail_send/views.py の編集

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

```bash
mkdir lib
```

>次の mail['password'] は変更して下さい。

```py:mail_send/lib/mail_yahoo.py
# -*- coding: utf-8 -*-
#
#	mail_yahoo.py
#
#						Dec/28/2018
# --------------------------------------------------------------------
import	sys
import	email
from email.mime.text import MIMEText
from email.utils import formatdate
# --------------------------------------------------------------------
from mail_send.lib.send_mail import send_mail_proc
# --------------------------------------------------------------------
def mail_yahoo_proc(mail_from,mail_to,subject,content):
	mail = {}
	mail['server'] = 'smtp.mail.yahoo.co.jp'
	mail['port'] = 587
	mail['usr'] = mail_from
	mail['password'] = '***secret***'
	mail['from'] = mail_from
	mail['to'] = mail_to

	message = MIMEText (
		content,
		'plain',
		)

	message['Subject'] = subject
	message['From'] = mail_from
	message['To'] = mail_to
	message['Date'] = formatdate()
#
	send_mail_proc(mail,message)
#
# --------------------------------------------------------------------
```

```py:mail_send/lib/send_mail.py
# -*- coding: utf-8 -*-
#
#	send_mail.py
#
#						May/20/2017
# --------------------------------------------------------------------
import	sys
import	socket
import	smtplib
import	email
from email.mime.text import MIMEText
from email.utils import formatdate
# --------------------------------------------------------------------
# [6]:
def send_mail_proc (mail,message):
	if (mail['port'] == 465):
		try:
			send_ssl (mail,message)
		except Exception as ee:
			sys.stderr.write ("*** error *** send_ssl ***\n")
			sys.stderr.write (str (ee) + "\n")
	elif (0 <= mail['server'].find ('plala.or.jp')):
		try:
			send_plain (mail,message)
		except Exception as ee:
			sys.stderr.write ("*** error *** send_plain ***\n")
			sys.stderr.write (str (ee) + "\n")
	else:
		send_mail_proc_s2 (mail,message)
#
# --------------------------------------------------------------------
# [6-2]:
def send_ssl (mail,message):
	ss = smtplib.SMTP_SSL (mail['server'],mail['port'])
	ss.ehlo ()
#	ss.starttls ()
	ss.ehlo ()
	ss.login (mail['usr'],mail['password'])
	ss.sendmail (
		mail['from'],
		[mail['to']],
		message.as_string (),
		)
	ss.close ()
#
# --------------------------------------------------------------------
# [6-4]:
def send_starttls (mail,message):
	ss = smtplib.SMTP (mail['server'],mail['port'])
	ss.ehlo ()
	ss.starttls ()
	ss.ehlo ()
	ss.login (mail['usr'],mail['password'])
	ss.sendmail (
		mail['from'],
		[mail['to']],
		message.as_string (),
		)
	ss.close ()
#
# --------------------------------------------------------------------
# [6-2]:
def send_mail_proc_s2 (mail,message):
	try:
		send_starttls (mail,message)
	except Exception as ee:
		sys.stderr.write ("*** error *** send_starttls ***\n")
		sys.stderr.write (str (ee) + "\n")
		try:
			send_plain (mail,message)
		except Exception as ee:
			sys.stderr.write ("*** error *** send_plain ***\n")
			sys.stderr.write (str (ee) + "\n")
			sys.stderr.write ("*** error *** send_plain ***\n")
			try:
				send_simple (mail,message)
			except Exception as ee:
				sys.stderr.write ("*** error *** send_simple ***\n")
				sys.stderr.write (str (ee) + "\n")
#
# --------------------------------------------------------------------
# [6-6]:
def send_plain (mail,message):
	sys.stderr.write ("*** send_plain *** start ***\n")
	ss = smtplib.SMTP (mail['server'],mail['port'])
	ss.ehlo ()
#	ss.starttls ()
#	ss.ehlo ()
	sys.stderr.write ("*** send_plain *** bbb ***\n")
	ss.login (mail['usr'],mail['password'])
	sys.stderr.write ("*** send_plain *** ccc ***\n")
	ss.sendmail (
		mail['from'],
		[mail['to']],
		message.as_string (),
		)
	ss.close ()
#
# --------------------------------------------------------------------
# [6-8]:
def send_simple (mail,message):
	sys.stderr.write ("*** send_simple *** start ***\n")
	ss = smtplib.SMTP (mail['server'],mail['port'])
#
	ss.sendmail (
		mail['from'],
		[mail['to']],
		message.as_string (),
		)

	ss.close ()
#
	sys.stderr.write ("*** send_simple *** end ***\n")
# --------------------------------------------------------------------
```

C) mail_send/views.py の修正
>次の　mail_from と mail_to は変更して下さい。

```py:mail_send/views.py
# --------------------------------------------------------------------
import	sys
import	socket
#
from mail_send.lib.send_mail import send_mail_proc
from mail_send.lib.mail_yahoo import mail_yahoo_proc

from django.shortcuts import render

from django.http import HttpResponse

# --------------------------------------------------------------------
def index(request):
    mail_proc01()
    str_out = "Good Afternoon<p />"
    str_out += "こんにちは<p />"
    return HttpResponse(str_out)

# --------------------------------------------------------------------
def mail_proc01():
    sys.stderr.write("*** 開始 ***\n")

    mail_from = 'aaabbb@yahoo.co.jp'
    mail_to = 'ccc@example.com'

    sys.stderr.write("to:" + mail_to + "\n")

    subject = 'Hello on Dec/28/2018 PM 17:00'

    content = 'こんにちは。\n'
    content += ' ' + socket.gethostname()

    mail_yahoo_proc(mail_from,mail_to,subject,content)

    sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------
```

D) 開発サーバーを起動

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

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

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