步骤一、在settings.py主配置文件中
#配置邮件服务器 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #采用smtp服务发送邮件 EMAIL_USE_TLS = False #使用tls,SMTP服务器通信时,是否启动TLS链接(安全链接)。 EMAIL_HOST = 'smtphz.qiye.163.com' #发邮件使用的服务器 EMAIL_PORT = 25 #主机的端口 EMAIL_HOST_USER = '发邮件的邮箱账户' ##自己的邮箱 EMAIL_HOST_PASSWORD = '邮箱的授权码' #密码 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER #默认发件人的邮箱redis_config={'host':'redis数据库的ip地址','port':端口号}
步骤二、写一个redis.py模块,在util包中
import redis
from 项目根目录.settings import redis_config
redis_confir = redis.Redis(host=redis_config['host'], port=redis_config['port'], decode_responses=True)
步骤三、写一个code.py模块,在util包中
import ramdom
class MakeCode:
def get_code(self,num=5):
lis1 = ['1','2','3','4','5','6','7','8','9']
for i in range(65, 90):
lis1.append(chr(i))
for i in range(97, 122):
lis1.append(chr(i))
l2 = random.sample(lis1,num)
return ''.join(l2)
makecode=MakeCode()
步骤四、写一个发送邮件的模块,email.py,util包
from 项目根目录.settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from util import redis
from util import code
from django.contrib.auth.models import User
class Send_emails:
def __init__(self):
self.send_user = EMAIL_HOST_USER
def register_mail(self, auth_email):
'''注册验证码'''
email_code = redis.makecode.get_code()
print(email_code)
redis_confir.set(auth_email,email_code, ex=60*5)
content = '您的邮箱验证码为 ' + email_code
try:
send_mail(
subject='xxx邮箱验证',
message=content,
from_email=EMAIL_HOST_USER,
recipient_list=[auth_email]
)
return {'code': '200', 'state': '发送邮件成功!'}
except Exception as e:
self.send_admin(e)
return {'code':400, 'state':'系统出现未知错误,已经通知系统管理员。'}
# 异常信息
def send_admin(self,content):
send_mail(
subject='xxx邮箱验证',
message=content,
from_email=EMAIL_HOST_USER,
recipient_list=[self.admin_email]
)