手记

django发送邮件

始于:项目学习中用户注册激活链接的邮件发送
学习于:_bobby老师的django+xadmin课程
1.在apps子项目群中新建文件夹utils,用于存放以后可能用到的方法
2.在utils文件夹下建立send_mail.py文件,用于存放发送邮件的接口函数
3.settings.py文件有关于发送邮件的配置:

	EMAIL_HOST = 'smtp.163.com'  #163邮箱SMTP服务器地址
	EMAIL_PORT = 25   #端口
	EMAIL_HOST_USER = 'm18737572516_1@163.com'   #发件人的邮箱
	EMAIL_HOST_PASSWORD = 'xxx'   #发件人邮箱密码
	EMAIL_USE_TLS = False  #tls协议,有True和False两种情况
	EMAIL_FROM = 'm18737572516_1@163.com'  #发件人的邮箱

4.定义发送邮件的函数:

def send_register_mail(email,send_type="register"):
    #实例化对象
    email_code = EmailVerifyRecord()
    code = random_str(12)
    email_code.email = email
    email_code.code = code
    email_code.send_type = send_type
    email_code.save()

    email_title = ''
    email_bobdy = ''

    if send_type == 'register':
        email_title = '注册验证'
        email_bobdy = '此为新用户注册本网站的激活链接,请点击:http://127.0.0.1:8000/users/activate/{0}'.format(code)

    send_status = send_mail(email_title,email_bobdy,EMAIL_FROM,[email])
    return send_status

注:1.EmailVerifyRecord是自定义的存储验证码的模型数据
2.send_mail是django自带的发送邮件的函数:from django.core.mail import send_mail
3.random_str()是自定义的验证码的生成:

from random import Random

def random_str(num=8):
    str = ''
    str1 = 'AaBbCc4DdEeFfalsk4jfjdlfjedr4lks8djlkdsjkljdsl64fjlksdjl4fkjlsdkfj8lkdsjglkje4rligfjolikre4'
    randoms = Random()
    for i in range(num):
        str += str1[randoms.randint(0,len(str1)-1)]
    return str
0人推荐
随时随地看视频
慕课网APP