之前尝试使用twilio发短信,实际测试后发现发多了以后会被屏蔽。所以之后尝试改成国内阿里云的短信服务
配置步骤参考了
https://blog.csdn.net/weixin_62917800/article/details/134116231
首先需要去短信服务里去申请资质、签名和模版,一般一天内就可以申请下来:
https://dysms.console.aliyun.com/domestic/text
之后点击右上角的头像创建AccessKey用于之后的编程
之后再快速学习和测试里,绑定测试号码,然后可以在调试界面看到自己对应的调试服务,点击发起调用后手机会收到短信~
之后点击右侧对应的Python平台可以看到对应代码,然后填上自己的key和id即可正常使用,使用前需要先安装一些阿里云的库
pip install alibabacloud_dysmsapi20170525 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install alibabacloud_tea_openapi -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install alibabacloud_tea_util -i https://pypi.tuna.tsinghua.edu.cn/simple
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Dysmsapi20170525Client:
"""
使用AK&SK初始化账号Client
@return: Client
@throws Exception
"""
# 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
# 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
config = open_api_models.Config(
# 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
access_key_id='LTAI5qHBkvqKLnsOMjApS1OPI',
# 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
access_key_secret='JPDDvC5g1C0LQ0LGHKCBM1o6rc9bsx'
)
# Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
@staticmethod
def main(
) -> None:
client = Sample.create_client()
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
sign_name='大聪明发送的告警信息',
template_code='SMS_47asdasd2380151',
phone_numbers='12345607308',
template_param='{"code":"1234"}'
)
runtime = util_models.RuntimeOptions()
try:
# 复制代码运行请自行打印 API 的返回值
client.send_sms_with_options(send_sms_request, runtime)
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
async def main_async(
) -> None:
client = Sample.create_client()
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
sign_name='大聪明发送的告警信息',
template_code='SMS_47asdasd2380151',
phone_numbers='12345607308',
template_param='{"code":"1234"}'
)
runtime = util_models.RuntimeOptions()
try:
# 复制代码运行请自行打印 API 的返回值
await client.send_sms_with_options_async(send_sms_request, runtime)
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
if __name__ == '__main__':
Sample.main()