Python + Djangoでメールを送信してみます
1.環境
windows10 home 64bit
Python 3.6.5
Django 2.0.4
2.アプリケーション作成
cmd.prompt
(venv) C:\data\python\myproject>python manage.py startapp sendmail
作成後の構成
myproject\sendmail
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ urls.py ・・・・・・(1)
│ views.py ・・・・・・(2)
│ __init__.py
※migrations、__pycache__は省略
3.アプリケーションの編集
(1)sendmail\urls.pyの作成
sendmail\urls.py
from django.urls import path
from . import views
app_name = 'sendmail'
urlpatterns = [
path('', views.index, name='index'),
]
※startappでは、urls.pyは作成されないので、作成してください
(2)sendmail\views.pyの編集
sendmail\views.py
from django.shortcuts import render
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect
def index(request):
"""題名"""
subject = "題名"
"""本文"""
message = "本文です\nこんにちは。メールを送信しました"
"""送信元メールアドレス"""
from_email = "information@myproject"
"""宛先メールアドレス"""
recipient_list = [
"apptest@apptest.com"
]
send_mail(subject, message, from_email, recipient_list)
return HttpResponse('<h1>email send complete.</h1>')
※ポイントは、「send_mail」の箇所だけです。
4.プロジェクトの設定
(1)myproject\settings.py
emailを送信するために、settings.pyを以下のように編集します。
EMAIL_BACKENDは、settings.pyの最後に追記しました。
myproject\settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sendmail', #追加
]
・・・・
# mail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'apptest'
EMAIL_HOST_PASSWORD = 'xxxxxxxx'
EMAIL_USE_TLS = False
開発環境で、smtpサーバに送信しない場合は、以下のようにすればconsoleに出力できるようです。
myproject\settings.py
# for email debug settings
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
(2)myproject\urls.py
以下の通りです。
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('sendmail/', include('sendmail.urls')), #"追加"
path('admin/', admin.site.urls),
]
5.動作確認
(1)サーバを起動します
cmd.prompt
(venv) C:\data\python\myproject>managed.py runserver
(2)http://localhost:8000/sendmail/にアクセスします
メールも届きました。