- 创建Django项目:例如我创建的项目叫:
django_send_email
- 创建一个App:例如我创建的App叫:
sendemail
- 再settings.py文件中加入app:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sendemail', # 新加入的app
]
- 编写视图文件view.py:
Django框架已经内置写好的发送邮件的代码,我们只要使用相应的库就能实现发送邮件
from django.shortcuts import render, HttpResponse
from django.core.mail import send_mail
from django_send_email import settings
def send_email(request):
result = send_mail(subject='测试',
from_email=settings.EMAIL_HOST_USER,
recipient_list=[settings.EMAIL_FROM],
fail_silently=False, message='内容')
return HttpResponse(result)
- 在sendemail的app下新建urls.py文件,编辑这个文件:
from django.urls import path
from . import views
app_name = 'sendemail'
urlpatterns = [
path('sendemail/', views.send_email, name='send_email'),
]
- 在django_send_email下的urls.py下加入:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('sendemail.urls')),
]
- 在settings.py文件中加入:
EMAIL_HOST = 'smtp.qq.com' # 邮件服务器地址
EMAIL_PORT = 25 # 端口号25 or 465
EMAIL_HOST_USER = '1343500013@qq.com' # 用户名,可以自定义
EMAIL_HOST_PASSWORD = 'iutefzddpdidijgd' # 邮箱授权码
EMAIL_USE_TLS = True # 默认
EMAIL_FROM = '1343500013@qq.com' # 发送人
- 运行项目,输入网址,项目正常运行。
项目源代码:下载地址