邮箱
django中自带的功能,因为登录注册都需要邮箱,因此新增了一个小的app——utils用来存放
# email_send.py
import random
from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJiKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str
def send_register_email(email, send_type = 'register'):
email_record = EmailVerifyRecord()
code = random_str(16)
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.save()
email_title = ''
email_body = ''
if send_type == 'register':
email_title = '慕学在线网注册激活链接'
email_body = '请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}'.format(code)
try:
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
except Exception,e:
print e
else:
print send_status
if send_type == 'forget':
email_title = '慕学在线网密码重置链接'
email_body = '请点击下面的链接重置你的密码:http://127.0.0.1:8000/reset/{0}'.format(code)
try:
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
except Exception,e:
print e
else:
print send_status
# setting 注意要开通邮箱的SMP服务,163邮箱中的密码是授权码,EMAIL_USE_TLS = False,QQ邮箱中这个参数可能需要改为True
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = '你的邮箱名'
EMAIL_HOST_PASSWORD = '你的授权码'
EMAIL_USE_TLS = False
EMAIL_FROM = '你的邮箱名'
#之后需要邮箱的时候调用这个函数就好了