1. 程式人生 > >django 傳送郵件配置

django 傳送郵件配置

拿qq郵箱當做發件箱舉例子,首先配置郵箱

在qq郵箱的賬戶設定裡面設定如下

 

得到第三方登陸授權碼

setting.py中設定如下:

# 傳送郵件設定
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #固定寫法
EMAIL_HOST = 'smtp.qq.com' #SMTP地址
EMAIL_PORT = 25 #SMTP埠
EMAIL_HOST_USER = '[email protected]' #傳送郵件的郵箱
EMAIL_HOST_PASSWORD = '******'  # 授權碼
EMAIL_SUBJECT_PREFIX = '[一念永恆的部落格] ' #為郵件Subject-line字首,預設是'[django]'
EMAIL_USE_TLS = True  # 與SMTP伺服器通訊時,是否啟動TLS連結(安全連結)預設false

view.py

區域性關鍵程式碼示例;

    if email != '':
        # 生成驗證碼
        code = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        now = int(time.time())
        send_code_time = request.session.get('send_code_time', 0)
        if now - send_code_time < 30:
            data['status'] = 'ERROR'
        else:
            request.session[send_for] = code
            request.session['send_code_time'] = now
            
            # 傳送郵件
            send_mail(
                '繫結郵箱',
                '驗證碼:%s' % code,
                '
[email protected]
', [email], fail_silently=False, ) data['status'] = 'SUCCESS' else: data['status'] = 'ERROR'