因爲項目在註冊、登陸、找回密碼 時須要發送短信驗證的功能,咱們使用騰訊雲短信作。python
爲何要用騰訊雲短信呢? 由於註冊就送 100條免費短信 的額度。shell
註冊一個騰訊雲帳戶,騰訊雲中提供了不少功能:雲服務器、雲存儲你、雲直播、雲短信等不少功能。小程序
註冊地址:https://cloud.tencent.com/服務器
註冊並要實名認證微信
建立應用並將應用中生成的
SDK AppID
和App Key
複製下來,以後經過python發送短信時須要用到。網絡
在騰訊雲短信簽名時須要認證,認證須要填寫簽名類型:網站、APP、小程序、公衆號,前三種須要提供企業資質等複雜的東西,我的公衆號認證會比較便捷,因此推薦我的開發的話使用 公衆號 進行簽名。app
so,我們須要先
申請一個公衆號
而後建立簽名
網站
註冊地址:https://mp.weixin.qq.com/3d
上述的準備工做作完中咱們開通相關服務並獲取到以下幾個值:
code
# 建立應用,獲取到 appid 和 appkey # 建立簽名,獲取 簽名內容 # 建立模板,獲取 模板ID
接下來開始使用Python發送短信。
安裝SDK
pip install qcloudsms_py
基於SDK發送短信
#!/usr/bin/env python # -*- coding:utf-8 -*- import ssl # ssl._create_default_https_context = ssl._create_unverified_context from qcloudsms_py import SmsMultiSender, SmsSingleSender from qcloudsms_py.httpclient import HTTPError def send_sms_single(phone_num, template_id, template_param_list): """ 單條發送短信 :param phone_num: 手機號 :param template_id: 騰訊雲短信模板ID :param template_param_list: 短信模板所需參數列表,例如:【驗證碼:{1},描述:{2}】,則傳遞參數 [888,666]按順序去格式化模板 :return: """ appid = 112142311 # 本身應用ID appkey = "8cc5b87123y423423412387930004" # 本身應用Key sms_sign = "Python之路" # 本身騰訊雲建立簽名時填寫的簽名內容(使用公衆號的話這個值通常是公衆號全稱或簡稱) sender = SmsSingleSender(appid, appkey) try: response = sender.send_with_param(86, phone_num, template_id, template_param_list, sign=sms_sign) except HTTPError as e: response = {'result': 1000, 'errmsg': "網絡異常發送失敗"} return response def send_sms_multi(phone_num_list, template_id, param_list): """ 批量發送短信 :param phone_num_list:手機號列表 :param template_id:騰訊雲短信模板ID :param param_list:短信模板所需參數列表,例如:【驗證碼:{1},描述:{2}】,則傳遞參數 [888,666]按順序去格式化模板 :return: """ appid = 112142311 appkey = "8cc5b87123y423423412387930004" sms_sign = "Python之路" sender = SmsMultiSender(appid, appkey) try: response = sender.send_with_param(86, phone_num_list, template_id, param_list, sign=sms_sign) except HTTPError as e: response = {'result': 1000, 'errmsg': "網絡異常發送失敗"} return response if __name__ == '__main__': result1 = send_sms_single("15131255089", 548760, [666, ]) print(result1) result2 = send_sms_single( ["15131255089", "15131255089", "15131255089", ],548760, [999, ]) print(result2)
騰訊雲短信後臺能夠進行 短信頻率 的限制。
可是,因爲咱們是免費用戶因此沒法進行設置,只能使用默認的配置(30秒發1條/1小時發5條/1天發10條)。