Gmail - Django

設定ファイルの変更

「 settings.py 」に以下を追加します。

env\myproject\myproject\settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '送信用のメールアドレス'
EMAIL_HOST_PASSWORD = 'アプリパスワード'

urls の変更

env\myproject\myproject\urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('mail/', include('mail.urls')),
]

env\myproject\mail\urls.py

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('send_mail/', views.send_email, name='send_mail'),
]

views

env\myproject\mail\views.py

from django.shortcuts import render, redirect

# Create your views here.
from django.core.mail import send_mail

def index(request):
  return render(request, 'mail/index.html')

def send_email(request):
    send_mail(
        'Hello, World',  # 件名
        'test',  # メッセージ
        'from@gmail.com',  # 送信元のメールアドレス
        ['to@gmail.com'],  # 送信先のメールアドレスのリスト
        fail_silently=False,
    )
    return redirect('/mail/')  # メール送信後に遷移するページ

templates

env\myproject\mail\templates\mail\index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="{% url 'send_mail' %}" method="post">
    {% csrf_token %}
    <button type="submit">Mail</button>
  </form>
</body>
</html>