短信驗證功能、郵箱驗證功能

發送短信

須要藉助第三方平臺來發送短信,如阿里雲、雲通信(對python3不友好)、騰訊雲。在這裏用的是騰訊雲來做爲示例html

騰訊雲中短信準備工做

1. 騰訊雲官網註冊、實名認證、登陸(不廢話、跳過)

2. 點擊頁面右上角「控制檯」

3. 點擊導航欄的雲產品,能夠看到各類產品,找到「短信」。第一次使用會調到「申請開通頁面」,勾選贊成、開始接入。(這是我的認證,企業認證還須要一些相關的認證材料)

4. 接入後有三大功能:應用列表、套餐包管理、SDK & API.

* 應用列表:管理應用的;
* 套餐包管理:管理套餐包的;
* SDK & API:就是一些相關的指南手冊(開發指南);

5. 在應用列表頁「添加應用」,添加後點進去(如應用名:技術棧)

6. 來到國內短信,點擊短信內容配置

7. 短信簽名 -> 建立簽名:要用到微信公衆號或小程序(微信公衆號註冊,首頁截圖),填寫見圖建立簽名

8. 短信正文 -> 建立正文模板:填寫見圖短信正文。

9. 等待審覈

# 後臺開發

更多短信發送參考SDK & API中的開發指南:文檔中心 > 短信 > SDK文檔 > Python SDK https://cloud.tencent.com/document/product/382/11672python

配置SDK

pip install qcloudsms_py

準備必要參數

# 短信應用 SDK AppID 以1400開頭
appid = 1400009099  
# 短信應用 SDK AppKey 根據本身的短信應用配置
appkey = "9ff91d87c2cd7cd0ea762f141975d1df37481d48700d70ac37470aefc60f9bad"
# 須要發送短信的手機號碼(非必填項,可在你的開發代碼中傳入)
phone_numbers = ["21212313123", "12345678902", "12345678903"]
# 短信模板ID,真實的模板 ID 須要在短信控制檯中申請
template_id = 7839  # 這裏的模板 ID`7839`只是示例,
# 簽名,使用的是`簽名內容`,而不是`簽名ID`。這裏的簽名"騰訊雲"只是示例,真實的簽名須要在短信控制檯中申請
sms_sign = "騰訊雲"  # 發寫個空字符串也行

指定模板 ID 單發短信

import random
from utils.logging import logger
from .settings import *
from qcloudsms_py import SmsSingleSender
ssender = SmsSingleSender(appid, appkey)
# 生成驗證碼
def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))
    return code

def send_sms(mobile, code, exp):
    """
    發送短信
    :param mobile: 電話號碼
    :param code: 驗證碼
    :param exp: 過時時間
    :return:
    """
    try:
        response = ssender.send_with_param(86, mobile, template_id, (code, exp), sign=sms_sign, extend="", ext="")
        # 短信發送成功的標識:沒有異常且response大字典中的result爲0
        if response and response['result']==0:
            return True
        logger.error('sms error: %s'% response['errmsg'])
        return
    except Exception as e:
        logger.error("sms error: %s" % e)
        return False
    
if __name__ == '__main__':
    code = get_code()
    print(code)
    result = send_sms('xxxxxxx',code,'1')  # 電話號碼,驗證碼,過時時間
    print(result)

郵箱驗證功能

from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import smtplib
import time

class EmailPro:
    def send_mail(self, to_email, code):
        email_host = 'smtp.163.com'  # 服務器地址 163郵箱"smtp.163.com"  qq郵箱"smtp.qq.com"都須要開通smtp權限
        sender = 'xxx@163.com'  # 發件人(本身的郵箱)
        password = 'xxx'  # 郵箱受權碼
        receiver = 'xxx@qq.com'  # 收件人
        msg = MIMEMultipart()
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        subject = now + '郵箱激活'
h = Header('發件人暱稱自定義', 'utf-8')
    h.append('<xxx@163.com>', 'ascii')
    msg["From"] = h
    msg['Subject'] = subject  # 標題
    msg['To'] = 'xxx'  # ...收件人...

    signature = '''
\n\t You are most welcome!
\n\t 點擊下面的按鈕激活郵箱
'''
    # text = MIMEText(signature, 'plain')  # 簽名
    # msg.attach(text)

    # 正文-圖片 只能經過html格式來放圖片,因此要註釋25,26行
    mail_msg = f'''
    
<p>\n\t You are most welcome!</p>
<p>\n\t 點擊下面的按鈕激活郵箱</p>
<button style="background-color: #31708f; border-radius: 3px"><a href="http://127.0.0.1:8000/user/email/active/?email={to_email}&code={code}" style="color: white;font-size: 25px;text-decoration: none">激活郵箱</a></button>
<p><img src="cid:image1"></p>
'''
    msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定圖片爲當前目錄
    fp = open(r'E:\rent_house\media\banner\3.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    # 定義圖片 ID,在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)

    # ctype = 'application/octet-stream'
    # maintype, subtype = ctype.split('/', 1)
    # 附件-圖片
    # image = MIMEImage(open(r'E:\rent_house\media\banner\3.jpg', 'rb').read(), _subtype=subtype)
    # image.add_header('Content-Disposition', 'attachment', filename='img.jpg')
    # msg.attach(image)
    # 附件-文件
    # file = MIMEBase(maintype, subtype)
    # file.set_payload(open(r'E:\rent_house\apps\utils\response.py', 'rb').read())
    # file.add_header('Content-Disposition', 'attachment', filename='test.txt')
    # encoders.encode_base64(file)
    # msg.attach(file)

    # 發送
    smtp = smtplib.SMTP()
    smtp.connect(email_host, 25)
    smtp.login(sender, password)
    smtp.sendmail(sender, to_email, msg.as_string())
    smtp.quit()
    print('success')
email_worker = EmailPro()
相關文章
相關標籤/搜索