python发送网页注册短信
时间: 2023-11-24 21:37:45 浏览: 82
python发送短信
要发送网页注册短信,需要使用第三方短信接口。以下是一个Python发送短信的示例代码,使用的是阿里云短信接口:
```python
import urllib.parse
import urllib.request
import json
def send_sms(phone_number, sign_name, template_code, template_param):
access_key_id = "your_access_key_id"
access_key_secret = "your_access_key_secret"
region_id = "cn-hangzhou"
action = "SendSms"
version = "2017-05-25"
params = {
"PhoneNumbers": phone_number,
"SignName": sign_name,
"TemplateCode": template_code,
"TemplateParam": json.dumps(template_param),
"RegionId": region_id,
"AccessKeyId": access_key_id,
"Format": "JSON",
"SignatureMethod": "HMAC-SHA1",
"SignatureVersion": "1.0",
"SignatureNonce": str(uuid.uuid1()),
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
}
# 签名
sorted_params = sorted(params.items(), key=lambda x: x[0])
canonicalized_query_string = ""
for (k, v) in sorted_params:
canonicalized_query_string += "&" + urllib.parse.quote(k) + "=" + urllib.parse.quote(v)
string_to_sign = "GET&%2F&" + urllib.parse.quote(canonicalized_query_string[1:])
h = hmac.new(bytes(access_key_secret + "&", "utf-8"), bytes(string_to_sign, "utf-8"), hashlib.sha1)
signature = base64.encodebytes(h.digest()).rstrip()
# 发送请求
url = "http://dysmsapi.aliyuncs.com/?Signature=" + urllib.parse.quote(signature) + canonicalized_query_string
with urllib.request.urlopen(url) as response:
response_text = response.read().decode("utf-8")
response_dict = json.loads(response_text)
if response_dict["Code"] == "OK":
return response_dict["RequestId"]
else:
raise Exception(response_dict["Message"])
```
使用时,需要替换掉示例代码中的`access_key_id`和`access_key_secret`为你的阿里云短信服务的访问密钥ID和访问密钥Secret,以及填写短信发送的手机号码、短信签名、短信模板号码和短信模板参数。
阅读全文