1、介绍
什么是华为云消息&短信(Message & SMS)服务?
消息&短信(Message & SMS)是华为云携手全球多家优质运营商和渠道,为企业用户(不包括个体工商户、个人独资企业、合伙企业等非法人主体或组织)提供单发、群发短信服务,同时可接收用户回复短信。
您将学到什么?
如何通过Java版SDK来体验消息&短信(Message & SMS)服务的发送短信功能。
2、开发时序图

3、前置条件
- 1、需要是华为云企业认证账号,并开通华为云MSGSMS云服务。
- 2、获取华为云开发工具包(SDK),您也可以查看安装Python SDK。使用服务端SDK前,您需要安装“huaweicloudsdksmsapi“。
pip install huaweicloudsdksmsapi
- 3、已具备开发环境 ,支持Python3及其以上版本。
- 4、已获取应用的Application Key(app_key)和Application Secret(app_secret)。请在华为云控制台“应用管理”页面上创建和查看您的Application Key和Application Secret。具体请参见 应用管理 。
- 5、已获得您要发送短信的通道号,由于通道号与签名关联,请在控制台“签名管理”页面上查看您的通道号,如果您还没有通道号,则您需要先提交签名申请,待签名申请通过后,系统会分配通道号。具体请参见签名管理。
- 6、已获取您要发送短信的模板ID,请在控制台“模板管理”页面上创建和查看您的模板ID。具体请参见模板管理。
4、接口参数说明
关于接口参数的详细说明可参见:
5、关键代码片段
5.1、创建SMSApiClient
@staticmethod
def main(args):
"""
Send an SMS message using a special AK/SK authentication algorithm.
When the MSGSMS is used to send SMS messages, the AK is app_key, and the SK is app_secret.
There will be security risks if the app_key/app_secret used for authentication is directly written into code.
We suggest encrypting the app_key/app_secret in the configuration file or environment variables for storage.
In this sample, the app_key/app_secret is stored in environment variables for identity authentication.
Before running this sample, set the environment variables CLOUD_SDK_MSGSMS_APPKEY and CLOUD_SDK_MSGSMS_APPSECRET.
CLOUD_SDK_MSGSMS_APPKEY indicates the application key (app_key), and CLOUD_SDK_MSGSMS_APPSECRET indicates the application secret (app_secret).
You can obtain the value from Application Management on the console or by calling the open API of Application Management.
"""
if "CLOUD_SDK_MSGSMS_APPKEY" not in os.environ or "CLOUD_SDK_MSGSMS_APPSECRET" not in os.environ:
print("Please config the environment CLOUD_SDK_MSGSMS_APPKEY and CLOUD_SDK_MSGSMS_APPSECRET first!")
return
ak = os.environ["CLOUD_SDK_MSGSMS_APPKEY"]
sk = os.environ["CLOUD_SDK_MSGSMS_APPSECRET"]
http_config = HttpConfig.get_default_config()
# To prevent API invoking failures caused by HTTPS certificate authentication failures, ignore the
# certificate trust issue to simplify the sample code.
# Note: Do not ignore the TLS certificate verification in the commercial version.
http_config.ignore_ssl_verification = True
"""
Creating an SmsApiClient Instance
This region of this example is of Beijing 4. Replace it with the actual value.
For detail, please refer to: https://support.huaweicloud.com/api-msgsms/sms_05_0019.html
"""
client = SMSApiClient.new_builder() \
.with_credentials(SMSApiCredentials(ak, sk)) \
.with_http_config(http_config) \
.with_region(Region(id="cn-north-4", endpoint="https://smsapi.cn-north-4.myhuaweicloud.com")).build()
5.1、调用发送短信接口(BatchSendSms)发送短信
http_code = SendSms.batch_send_sms(client)
@staticmethod
def batch_send_sms(client):
request = BatchSendSmsRequest(
body=BatchSendSmsRequestBody(
# Channel ID for sending SMS messages.
_from="8824110605***",
# List of numbers that receive SMS messages.
# Note: When there are multiple numbers, do not contain spaces between the numbers.
to="+86137****3774,+86137****3776",
# Template Id
template_id="1d18a7f4e1b84f6c8fc1546b48b3baea",
# Template parameter, which must be enclosed in square brackets ([]).
template_paras="[\"123\",\"456\",\"789\"]",
# Status report callback URL. Set this parameter to a valid value. If status reports are not
# required, you do not need to set this parameter.
status_callback="https://test/report"
)
)
# Invoke the SDK interface to send an SMS message.
try:
response = client.batch_send_sms(request)
print("Batch send sms result: {}", response)
return response.status_code
except ClientRequestException as e:
print("Batch send sms request exception: {}", str(e.status_code))
print("Batch send sms request exception error message: {}", e.error_msg)
except ServerResponseException as e:
print("Batch send sms response exception: {}", str(e.status_code))
print("Batch send sms response exception error message: {}", e.error_msg)
return http.client.INTERNAL_SERVER_ERROR
5.2、调用发送分批短信接口(BatchSendDiffSms)发送短信
http_code = SendSms.batch_send_diff_sms(client)
@staticmethod
def batch_send_diff_sms(client):
# Construct a request for sending SMS messages in batches.
request = BatchSendDiffSmsRequest(
body=BatchSendDiffSmsRequestBody(
# Channel ID for sending SMS messages.
_from="8824110605***",
# Status report callback URL. Set this parameter to a valid value. If status reports are not
# required, you do not need to set this parameter.
status_callback="https://test/report",
# Content of the first batch of group SMS messages
sms_content=[
SmsContent(
# List of SMS Recipient Numbers
to=["+86137****3774", "+86137****3775"],
# Template Id
template_id="1d18a7f4e1b84f6c8fc1546b48b3baea",
# Template Parameters
template_paras=["1", "23", "45"]
),
SmsContent(
# List of SMS Recipient Numbers
to=["+86137****3777"],
# Template Id
template_id="7824a51b3cc34976919a5418f637d0fb",
# Template Parameters
template_paras=["3", "4", "5"]
)
]
)
)
# Invoke the SDK interface to send SMS messages in batche
try:
response = client.batch_send_diff_sms(request)
print("Batch send diff sms result: {}", response)
return response.status_code
except ClientRequestException as e:
print("Batch send diff sms request exception: {}", str(e.status_code))
print("Batch send diff sms request exception error message: {}", e.error_msg)
except ServerResponseException as e:
print("Batch send diff sms response exception: {}", str(e.status_code))
print("Batch send diff sms response exception error message: {}", e.error_msg)
return http.client.INTERNAL_SERVER_ERROR
6、运行结果
发送短信(BatchSendSms)
{
"code": "000000",
"description": "Success",
"result": [{
"createTime": "2024-12-12T07:59:37Z",
"from": "8824110605***",
"originTo": "+86137****3774",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_2942603",
"status": "000000",
"countryId": "CN",
"total": 1
}, {
"createTime": "2024-12-12T07:59:37Z",
"from": "8824110605***",
"originTo": "+86137****3776",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_2942604",
"status": "000000",
"countryId": "CN",
"total": 1
}]
}
发送分批短信(BatchSendDiffSms)
{
"code": "000000",
"description": "Success",
"result": [{
"createTime": "2024-12-12T07:59:37Z",
"from": "8824110605***",
"originTo": "+86137****3774",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_2942950",
"status": "000000",
"countryId": "CN",
"total": 1
}, {
"createTime": "2024-12-12T07:59:37Z",
"from": "8824110605***",
"originTo": "+86137****3775",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_2942951",
"status": "000000",
"countryId": "CN",
"total": 1
}, {
"createTime": "2024-12-12T07:59:37Z",
"from": "8824110605***",
"originTo": "+86137****3777",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_2942952",
"status": "000000",
"countryId": "CN",
"total": 1
}]
}
7、参考
本示例的代码工程仅用于简单演示,实际开发过程中应严格遵循开发指南。访问以下链接可以获取详细信息:开发指南