Django之邮箱验证(在dango中运行,推荐使用,成功率很高)

view函数中

from django.core.mail import EmailMultiAlternatives 
from django.http import JsonResponse

def send_message(request):
	result = {'state':'error', 'data':''} #定义一个字典,用来记录运行情况
	try:
		subject = '这是一个来自django的邮件' #主题
		text_content = 'hello django' #text文本记录
		html_content = '<p style="color:red">its easy to learn python, never give up</p>'#html文本
		message = EmailMultiAlternatives(subject,text_content,'[email protected]',[[email protected]])#参数分别是邮件标题,文本内容,寄件人地址,收件人地址
		message.attach_alternative(html_content,'text/html') 
		message.send()
	except Exception as e :
		result['data'] = str(e) #发送失败记录错误
	else:
		result['state'] = 'success' #发送成功,记录成功
		result['data'] = 'success'
	finally:
		return JsonResponse(result)  #返回result信息

settings.py中加入

EMAIL_HOST_USER = '[email protected]' #寄件人地址
EMAIL_HOST_PASSWORD = 'xxxxx' #激活码,通过163邮箱设置中,自行设置
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = '994'

配置路由后,运行结果如下

在这里插入图片描述

之后就可以在邮箱中查看了

猜你喜欢

转载自blog.csdn.net/weixin_44183162/article/details/88427534