django 增加驗證郵箱功能
阿新 • • 發佈:2019-01-02
在user資料夾下新建python包,utils
在包內新建檔案email_send.py,其中包括驗證字串隨機碼的產生,資料庫的儲存和email的傳送
# -*- coding: utf-8 -*- # 作者:神祕藏寶室 # 日期:2019/1/1 22:21 from random import Random from django.core.mail import send_mail from users.models import EmailVerifyRecord from waaaxWeb.settings import EMAIL_FROM def random_str(randomlength=8): str = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' length = len(chars) - 1 random = Random() for i in range(randomlength): str += chars[random.randint(0, length)] return str def send_registr_email(email, sendtpye='register'): email_record = EmailVerifyRecord() code = random_str(16) email_record.code = code email_record.email = email email_record.send_type = sendtpye email_record.save() email_title = '' email_body = '' if sendtpye == 'register': email_title = u'維可思電子網註冊啟用連結' email_body = u'請點選下面的連結啟用您的賬號:http://127.0.0.1:8000/active/{0}'.format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: pass else: pass
因為用到傳送email需要在settings下設定EMAIL的屬性
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp-mail.outlook.com' #SMTP地址 例如: smtp.163.com
EMAIL_PORT = 25 #SMTP埠 例如: 25
EMAIL_HOST_USER = '[email protected]' #qq的郵箱 例如: [email protected]
EMAIL_HOST_PASSWORD = '' #我的郵箱密碼 例如 xxxxxxxxx
EMAIL_SUBJECT_PREFIX = u'django' #為郵件Subject-line字首,預設是'[django]'
EMAIL_USE_TLS = True #與SMTP伺服器通訊時,是否啟動TLS連結(安全連結)。預設是false
EMAIL_FROM = '[email protected]'