1.这里采用163邮箱配置,其他的类似
再使用之前,先确定你要使用的邮箱是什么邮箱,是qq的还是163的还是其他,一般需要到相对应的有相中找到授权码,一般是不支持直接使用邮箱密码的,授权码用来替代密码。
在者就是这里使用的是SMTP协议来进行发件,因此需要开启邮箱的相对应的服务。授权码和SMTP服务开启如下图:
第一步
第二步,开启配置
第三步,django中settings的配置
# 固定写法设置Email引擎
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com' # SMTP 服务器地址
EMAIL_PORT = 25 # SMTP服务的端口号
EMAIL_HOST_USER = '[email protected]' # 邮件发送者的邮箱
EMAIL_HOST_PASSWORD = 'ZHVNxxxxxxxECIGY' # 你申请的授权码(略)
EMAIL_USE_TLS = False # 与SMTP服务器通信时,是否启用安全模式
# 发送者 <只能是自己的邮箱>
EMAIL_FROM = 'python后端开发<[email protected]>'
第四步,url(自定义)
from django.urls import path
from app01 import views
urlpatterns = [
path('t6/', views.t6),
]
第五步,view
# 发送邮箱
def t6(request):
subject = 'python开发之路' # 主题
from_email = settings.EMAIL_FROM # 发件人,在settings.py中已经配置
receiver = ['[email protected]', '[email protected]'] # 邮件接收者列表
# 发送的消息
message = 'hello word' # 发送普通的消息使用的时候message
# meg_html会覆盖message,如果有标签,推荐用meg_html
meg_html = '<a href="http://www.baidu.com">点击跳转</a>'
# send_mail(subject=subject, from_email=from_email, recipient_list=receiver, message=message)
send_mail(subject=subject, from_email=from_email, recipient_list=receiver, html_message=meg_html, message=message)
return HttpResponse('ok')