1. 程式人生 > >Django筆記(Django郵件傳送、Django郵箱驗證碼實現)

Django筆記(Django郵件傳送、Django郵箱驗證碼實現)

1.settings.py 配置

注意:要開啟IMAP服務  才能傳送郵件  ,在郵箱設定裡的賬戶設定中

# 郵件配置
EMAIL_USE_SSL = True

EMAIL_HOST = 'smtp.qq.com'  # 如果是 163 改成 smtp.163.com

EMAIL_PORT = 465

EMAIL_HOST_USER = environ.get("EMAIL_SENDER") # 帳號

EMAIL_HOST_PASSWORD = environ.get("EMAIL_PWD")  # 授權碼(****)
# 預設郵件
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

2.views 檢視

from django.core.mail import send_mail, send_mass_mail

def send_my_email(req):
    title = "美團騎手offer"
    msg = "恭喜你成為美團騎手"
    email_from = settings.DEFAULT_FROM_EMAIL
    reciever = [
        '[email protected]'
    ]
    # 傳送郵件
    send_mail(title, msg, email_from, reciever)
    return HttpResponse("ok")

3.1views 檢視  (郵件中傳送頁面)

def send_email_v1(req):
    title = "美團騎手offer"
    msg = " "
    email_from = settings.DEFAULT_FROM_EMAIL
    reciever = [
        '[email protected]'
    ]
    # 載入模板
    template = loader.get_template('email.html')
    # 渲染模板
    html_str = template.render({"msg": "123456"})
    print(html_str)
    # 傳送郵件
    send_mail(title, msg, email_from, reciever, html_message=html_str)
    return HttpResponse("ok")

3.2  前端

<h1>好睏好無聊</h1>
請點選一個快樂的連結 <a href="https://blog.csdn.net/ding_312">快樂源泉</a>
{{ msg }}

4.郵箱驗證碼的實現

4.1 生成隨機字串

import uuid
import hashlib


def get_random_str():
    uuid_val = uuid.uuid4()
    uuid_str = str(uuid_val).encode("utf-8")
    md5 = hashlib.md5()
    md5.update(uuid_str)
    return md5.hexdigest()

4.2 拼接啟用連結url,載入啟用模板並進行渲染

def verify(req):
    if req.method == "GET":
        return render(req, 'verify.html')
    else:
        param = req.POST
        email = param.get('email')
        # 生成隨機字元
        random_str = get_random_str()
        # 拼接驗證連結(加網址)
        url = "http://118.24.95.20:8000/dj06app/active/" + random_str
        # 載入啟用模板
        tmp = loader.get_template('active.html')
        # 渲染
        html_str = tmp.render({'url': url})

        title = "美團騎手offer"
        msg = " "
        email_from = settings.DEFAULT_FROM_EMAIL
        reciever = [
            # '[email protected]'
            email,
        ]
        send_mail(title, msg, email_from, reciever, html_message=html_str)
        # 記錄 token 對應的郵箱是誰 v  k
        cache.set(random_str, email, 120)
        return HttpResponse('ok')

4.3 拿引數對應的快取資料,來自找郵箱對應的使用者,啟用使用者

def active(req, random_str):
    # 拿引數對應的快取資料
    res = cache.get(random_str)
    if res:
        # 通過郵箱找到對應使用者
        # 給使用者的狀態欄位做更新,從未啟用變成啟用狀態
        return HttpResponse(res+"啟用成功")
    else:
        return HttpResponse("驗證連結無效")

4.4 前端,輸入傳送郵箱頁面

<form action="/dj06app/verify" method="post" style="text-align: center">
    <input type="text" placeholder="郵箱" name="email">
    <br>
    <input type="submit" value="傳送">

傳送郵件生成隨機url頁面

歡迎註冊 澳門賭城會員 想要體驗 <span style="color: red;text-decoration: underline">美女荷官</span>
<br>
請點選 下面的連線
<p>
    <a href="{{url}}">{{url}}</a>
</p>

5. 一次傳送多個郵件

def send_many_email(req):
    title = "美團騎手offer"
    content1 = "該點外賣啦"
    email_from = settings.DEFAULT_FROM_EMAIL
    reciever1 = [
        '[email protected]',
        '[email protected]',
        '[email protected]',
    ]
    content2 = "吃飯睡覺不想敲程式碼"
    # 郵件1
    msg1 = (title, content1, email_from, reciever1)
    # 郵件2
    msg2 = ("渣渣們", content2, email_from, ['[email protected]', '[email protected]'])
    send_mass_mail((msg1,msg2), fail_silently=True)
    return HttpResponse("傳送好了")

send_mail 和  send_mass_mail 的區別

send_mail 每傳送一封郵件 就要和SMTP服務 做一次連結

send_mass_mail 可以一次連結 傳送多封郵件

celery非同步傳送郵件

(celery在我的其他博文中有介紹)

1. 在tasks.py 檔案中寫郵件任務

from celery import task
from django.core.mail import send_mail
from django.conf import settings
import time


@task
def send_email(email):
    title = '郵件的標題'
    msg = '非同步操作'
    from_email = settings.DEFAULT_FROM_EMAIL
    recievers = [email, ]
    send_mail(
        title,
        msg,
        from_email,
        recievers,
        # 傳送異常時不提示
        fail_silently=True
    )

2. 在views 檢視中呼叫郵件函式

from django.http import HttpResponse
from django.shortcuts import render
from .tasks import first_task, send_email


# Create your views here.

def first_celery(req):
    # 任務引數名.delay(引數)
    first_task.delay(4)
    send_email.delay("[email protected]")
    return HttpResponse("ok")

3. 實現非同步傳送(增強使用者體驗感)