标签:目标 host 直接 rom 验证码 返回 author 找回密码 包含
问题:
对于一些错误信息或用户注册账号的时候,需要给用户发送邮件进行验证。
以用户注册发邮件为例子,用户向后端提起注册,后端收到用户邮箱,对邮箱格式进行验证,然后发送邮件,邮件内容中包括邮件标题、邮件内容、邮件来源、邮件目标地址,一般验证中,会包含随机字符串和激活url地址
那,如何解决?
1. 建立一个utils目录,建立一个send_email.py文件, EmailVerifyRecord 是models中一个保存验证码信息的表
# !/usr/bin/python3 # _*_ encoding:utf-8 _*_ __author__ = ‘beimenchuixue‘ __blog__ = ‘http://www.cnblogs.com/2bjiujiu/‘ from django.core.mail import send_mail from users.models import EmailVerifyRecord from MxOline.settings import EMAIL_FROM import random def to_send_email(email, _type=‘register‘): """发送邮件""" email_rcode = EmailVerifyRecord() # 注册发送验证邮件 if _type == ‘register‘: random_code = get_random_code() email_title = ‘慕学在在线网注册验证‘ email_body = ‘点击连接完成激活: http://127.0.0.1:8000/active/{random_code}/{_type}‘.format(random_code=random_code, _type=_type) # 保存验证码 email_rcode.code = random_code email_rcode.send_type = _type email_rcode.email = email email_rcode.save() # 真正启动Django自带的发送邮件功能,邮件标题,邮件内容,邮件来源,发给谁 email_status = send_mail(subject=email_title, message=email_body, from_email=EMAIL_FROM, recipient_list=[email]) return email_status # 忘记密码发送验证邮件 if _type == ‘forget‘: random_code = get_random_code() email_title = ‘慕学在在线网找回密码‘ email_body = ‘点击连接完成激活: http://127.0.0.1:8000/active/{random_code}/{_type}‘.format(random_code=random_code, _type=_type) # 保存验证码 email_rcode.code = random_code email_rcode.send_type = _type email_rcode.email = email email_rcode.save() # 真正启动Django自带的发送邮件功能,邮件标题,邮件内容,邮件来源,发给谁 email_status = send_mail(subject=email_title, message=email_body, from_email=EMAIL_FROM, recipient_list=[email]) return email_status def get_random_code(length=8): """获得随机字符串""" code = ‘‘ choice_str = ‘abcdefghijklmnopqrstuvwxyz0123456789‘ for _ in range(length): random_str = random.choice(choice_str) code += random_str return code
2. 在setting中添加邮箱参数配置
# 邮箱设置,需要在邮箱中开启smtp服务 EMAIL_HOST = ‘smtp.163.com‘ EMAIL = 25 EMAIL_HOST_USER = ‘自己的邮箱地址‘ EMAIL_HOST_PASSWORD = ‘邮箱密码‘ EMAIL_USE_TIS = False EMAIL_FROM = ‘自己的邮箱地址‘
3. 在view中导入,直接调用,并把邮箱传入,这个函数会返回邮箱状态,为1表示发送成功
status = to_send_email(username, ‘register‘)
标签:目标 host 直接 rom 验证码 返回 author 找回密码 包含
原文地址:http://www.cnblogs.com/2bjiujiu/p/7452720.html