你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Important
短信功能取决于所使用的电话号码和所在的国家/地区,具体取决于 Azure 帐单邮寄地址。 For more information, see Subscription eligibility.
通过使用 Azure CLI 中的通信模块发送短信,开始使用 Azure 通信服务。
完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。
Prerequisites
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- 活动的通信服务资源和连接字符串。 创建通信服务资源。
- 支持短信的电话号码、短代码或字母数字发送者 ID。 获取电话号码。
- The latest Azure CLI version for your operating system.
Prerequisite check
- 在终端或命令窗口中,运行
az --version
检查是否安装了 Azure CLI。
Setting up
安装通信模块
若要安装通信模块,请在终端或命令窗口中运行以下命令。
az extension add --name communication
登录 Azure CLI
你需要登录到 Azure CLI。 可以从终端运行 az login
命令并提供凭据进行登录。
确保使用正确的订阅
如果帐户中有多个订阅,请确保使用本教程的正确订阅。
在终端或命令窗口中,运行以下命令来检查当前订阅。
az account show
如果需要更改订阅,可以通过运行以下命令来进行更改。
az account set --subscription "<yourSubscriptionId>"
需要将 <yourSubscriptionId>
替换为实际订阅 ID,可在 Azure 门户的“订阅”部分找到该 ID。
(可选)使用 Azure CLI sms 操作而无需传入连接字符串
可以配置 AZURE_COMMUNICATION_CONNECTION_STRING
环境变量来使用 Azure CLI sms 操作,而无需使用 --connection_string
来传入连接字符串。 若要配置环境变量,请打开控制台窗口,然后从以下选项卡中选择操作系统。 将 <yourConnectionString>
替换为实际的连接字符串。
打开控制台窗口并输入以下命令:
setx AZURE_COMMUNICATION_CONNECTION_STRING "<yourConnectionString>"
添加环境变量后,可能需要重启任何正在运行的、需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。
Operations
发送 1:1 短信
要将短信发送给单个收件人,请使用单个收件人电话号码从 sms 模块调用 send
方法。
az communication sms send --sender "<fromPhoneNumber>" --recipient "<toPhoneNumber>" --message "Hello world via SMS for Azure CLI!" --connection-string "<yourConnectionString>"
在代码中进行下述替换:
- 将
<fromPhoneNumber>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<toPhoneNumber>
替换为要向其发送消息的电话号码。 - 将
<yourConnectionString>
替换为你的连接字符串。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 <fromPhoneNumber>
的值也可以是短代码(例如 23456)或字母数字发送者 ID(例如 CONTOSO)。
发送 1:N 短信
要将短信发送给一组收件人,请使用多个收件人电话号码从 sms 模块调用 send
方法。
az communication sms send --sender "<fromPhoneNumber>" --recipient "<toPhoneNumber1>" "<toPhoneNumber2>" "<toPhoneNumber3>" --message "Hello world via SMS for Azure CLI!" --connection-string "<yourConnectionString>"
在代码中进行下述替换:
- 将
<fromPhoneNumber>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<toPhoneNumberN>
替换为要向其发送消息的第 N 个电话号码。 - 将
<yourConnectionString>
替换为你的连接字符串。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 该值 <fromPhoneNumber>
也可以是短代码,例如 23456 或字母数字发送方 ID,例如 CONTOSO。
通过使用通信服务 C# 短信 SDK 发送短信,开始使用 Azure 通信服务。
完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。
Note
请参阅 Azure 示例 GitHub 上的最终代码 ,使用 .NET 发送短信。
Prerequisites
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- 适用于你的操作系统的最新版 .NET Core SDK。
- 活动的通信服务资源和连接字符串。 创建通信服务资源。
- 支持短信的电话号码、短代码或字母数字发送者 ID。 获取电话号码。
Prerequisite check
- 在终端或命令窗口中,运行
dotnet
命令查看是否安装 .NET SDK。 - To view the phone numbers that are associated with your Communication Services resource, sign in to the Azure portal and locate your Communication Services resource. In the navigation pane on the left, select Phone numbers.
设置应用程序环境
若要设置用于发送消息的环境,请执行以下部分中所述的步骤。
新建 C# 应用程序
在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用
dotnet new
命令创建名为SmsQuickstart
的新控制台应用。 This command creates a simple "Hello World" C# project with a single source file, Program.cs.dotnet new console -o SmsQuickstart
将目录更改为新创建的应用文件夹,并使用
dotnet build
命令编译应用程序。cd SmsQuickstart dotnet build
安装包
仍在应用程序目录中操作,使用以下命令安装适用于 .NET 的 Azure 通信服务短信 SDK 包。
dotnet add package Azure.Communication.Sms --version 1.0.0
Add a
using
directive to the top of Program.cs to include theAzure.Communication
namespace.using System; using System.Collections.Generic; using Azure; using Azure.Communication; using Azure.Communication.Sms;
Object model
以下类和接口用于处理适用于 C# 的 Azure 通信服务短信 SDK 的某些主要功能。
Name | Description |
---|---|
SmsClient | 所有短信功能都需要此类。 使用订阅信息对其进行实例化,然后使用它发送短信。 |
SmsSendOptions | 此类提供用于配置传送报告的选项。 如果 enable_delivery_report 设置为 True,则在传送成功时将发出一个事件。 |
SmsSendResult | 此类包含来自短信服务的结果。 |
验证客户端
Open Program.cs in a text editor and replace the body of the Main
method with code to initialize an SmsClient
with your connection string. 以下代码从名为 COMMUNICATION_SERVICES_CONNECTION_STRING
的环境变量中检索资源的连接字符串。 了解如何管理资源的连接字符串。
// This code retrieves your connection string
// from an environment variable.
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
SmsClient smsClient = new SmsClient(connectionString);
发送 1:1 短信
若要将短信发送给单个收件人,请从 SmsClient 调用 Send
或 SendAsync
函数。 Add this code to the end of the Main
method in Program.cs:
SmsSendResult sendResult = smsClient.Send(
from: "<from-phone-number>",
to: "<to-phone-number>",
message: "Hello World via SMS"
);
Console.WriteLine($"Sms id: {sendResult.MessageId}");
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<to-phone-number>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 该值 <from-phone-number>
也可以是短代码,例如 23456 或字母数字发送方 ID,例如 CONTOSO。
发送包含选项的 1: N 短信
若要将短信发送到接收者列表,请从 SmsClient 调用 Send
或 SendAsync
函数并提供接收者电话号码列表。 还可以提供可选参数,以指定是否应启用传送报告,以及设置自定义标记。
Response<IReadOnlyList<SmsSendResult>> response = smsClient.Send(
from: "<from-phone-number>",
to: new string[] { "<to-phone-number-1>", "<to-phone-number-2>" },
message: "Weekly Promotion!",
options: new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL
{
Tag = "marketing", // custom tags
});
IEnumerable<SmsSendResult> results = response.Value;
foreach (SmsSendResult result in results)
{
Console.WriteLine($"Sms id: {result.MessageId}");
Console.WriteLine($"Send Result Successful: {result.Successful}");
}
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<to-phone-number-1>
和<to-phone-number-2>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 该值 <from-phone-number>
也可以是短代码,例如 23456 或字母数字发送方 ID,例如 CONTOSO。
enableDeliveryReport
参数是一个可选参数,可用于配置传送报告。 如果你想要在传送短信后发出事件,则此功能很有用。 请参阅处理短信事件快速入门,了解如何为短信配置传送报告。
可以使用 Tag
参数将标记应用于传送报告。
使用消息连接全局发送短信
Important
Azure 通信服务的这一功能目前以预览版提供。 预览版中的功能已公开发布,可供所有新客户和现有Microsoft客户使用。
预览版 API 和 SDK 在没有服务级别协议的情况下提供。 建议不要将它们用于生产工作负荷。 某些功能可能不受支持,或者功能可能受到限制。
有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款。
如果使用通过消息连接预配的电话号码,则可以使用标准 Azure 通信服务 SDK 发送短信。 唯一的区别是必须包含 MessagingConnect
对象来指定合作伙伴名称和 API 密钥。
Response<IReadOnlyList<SmsSendResult>> response = smsClient.Send(
from: "<from-messaging-connect-number>",
to: new string[] { "<to-phone-number-1>", "<to-phone-number-2>" },
message: "Weekly Promotion!",
options: new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL
{
Tag = "marketing", // custom tags
MessagingConnect = new MessagingConnectOptions("<partner-api-key>", "infobip")
});
IEnumerable<SmsSendResult> results = response.Value;
foreach (SmsSendResult result in results)
{
Console.WriteLine($"Sms id: {result.MessageId}");
Console.WriteLine($"Send Result Successful: {result.Successful}");
}
替换以下值:
<from-messaging-connect-number>
:通过 Messaging Connect 获取并链接到 ACS 资源的电话号码。<to-phone-number-1>
和<to-phone-number-2>
:收件人电话号码。<partner-api-key>
:来自消息连接合作伙伴(例如 Infobip)的 API 密钥。
Tip
想要了解有关全局消息传递的详细信息? 查看 “消息连接”页
Warning
电话号码必须遵循 E.164 国际标准格式(例如 +14255550123)。 <rom-messaging-connect-number>
必须是已预配并同步到 ACS 资源的 Messaging Connect 号码或动态 Alpha 发送方 ID(例如 CONTOSO)。
enableDeliveryReport
参数是一个可选参数,可用于配置传送报告。 如果你想要在传送短信后发出事件,则此功能很有用。 请参阅处理短信事件快速入门,了解如何为短信配置传送报告。 可以使用 Tag
参数将标记应用于传送报告。
运行代码
从应用程序目录使用 dotnet run
命令运行应用程序。
dotnet run
Sample code
从 Azure 示例 GitHub 下载示例应用 ,使用 .NET 发送短信。
开始使用 Azure 通信服务,使用通信服务 JavaScript SMS SDK 发送短信。
完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。
Note
请参阅最终的代码 Azure 示例 GitHub 使用 JavaScript 发送短信。
Prerequisites
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- Node.js Active LTS and Maintenance LTS versions (8.11.1 and 10.14.1 are recommended).
- 活动的通信服务资源和连接字符串。 创建通信服务资源。
- 支持短信的电话号码、短代码或字母数字发送者 ID。 获取电话号码。
Prerequisite check
- 在终端或命令窗口中,运行
node --version
以查看是否安装了 Node.js。 - To view the phone numbers that are associated with your Communication Services resource, sign in to the Azure portal and locate your Communication Services resource. In the navigation pane on the left, select Phone numbers.
设置应用程序环境
若要设置用于发送消息的环境,请执行以下部分中所述的步骤。
创建新的 Node.js 应用程序
打开终端或命令窗口,运行以下命令以便为应用创建新目录,然后导航到该目录。
mkdir sms-quickstart && cd sms-quickstart
Run the following command to create a package.json file with default settings.
npm init -y
Use a text editor to create a file called send-sms.js in the project root directory.
In the following sections, add all the source code for this quickstart to the send-sms.js file that you created.
安装包
使用 npm install
命令安装适用于 JavaScript 的 Azure 通信服务短信 SDK。
npm install @azure/communication-sms --save
The --save
option lists the library as a dependency in your package.json file.
Object model
以下类和接口用于处理适用于 Node.js 的 Azure 通信服务短信 SDK 的某些主要功能。
Name | Description |
---|---|
SmsClient | 所有短信功能都需要此类。 使用订阅信息对其进行实例化,然后使用它发送短信。 |
SmsSendRequest | 此接口是用于生成短信请求的模型。 你将使用它来配置接收者和发送者电话号码以及短信内容。 |
SmsSendOptions | 此接口提供用于配置传送报告的选项。 如果 enableDeliveryReport 设置为 true ,当传送成功时会发出一个事件。 |
SmsSendResult | 此类包含来自短信服务的结果。 |
验证客户端
To authenticate a client, you import the SmsClient from the SDK and instantiate it with your connection string. 可以从环境变量中检索资源的连接字符串。 例如,本部分中的代码从 COMMUNICATION_SERVICES_CONNECTION_STRING
环境变量中检索连接字符串。 了解如何管理资源的连接字符串。
若要导入客户端并将其实例化,请执行以下操作:
Create a file named send-sms.js.
Add the following code to send-sms.js.
const { SmsClient } = require('@azure/communication-sms');
// This code retrieves your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];
// Instantiate the SMS client.
const smsClient = new SmsClient(connectionString);
发送 1:N 短信
若要将短信发送到接收者列表,请从 SmsClient 调用 send
函数并提供接收者电话号码列表。 如果要向单个接收者发送消息,请仅在列表中包含一个号码。 Add this code to the end of send-sms.js:
async function main() {
const sendResults = await smsClient.send({
from: "<from-phone-number>",
to: ["<to-phone-number-1>", "<to-phone-number-2>"],
message: "Hello World 👋🏻 via SMS"
});
// Individual messages can encounter errors during sending.
// Use the "successful" property to verify the status.
for (const sendResult of sendResults) {
if (sendResult.successful) {
console.log("Success: ", sendResult);
} else {
console.error("Something went wrong when trying to send this message: ", sendResult);
}
}
}
main();
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<to-phone-number-1>
和<to-phone-number-2>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 <from-phone-number>
的值也可以是短代码(例如 23456)或字母数字发送者 ID(例如 CONTOSO)。
发送包含选项的 1: N 短信
还可以提供一个选项对象,以指定是否应启用传送报告,以及设置自定义标记。
async function main() {
const sendResults = await smsClient.send({
from: "<from-phone-number>",
to: ["<to-phone-number-1>", "<to-phone-number-2>"],
message: "Weekly Promotion!"
}, {
// Optional parameters
enableDeliveryReport: true,
tag: "marketing"
});
// Individual messages can encounter errors during sending.
// Use the "successful" property to verify the status.
for (const sendResult of sendResults) {
if (sendResult.successful) {
console.log("Success: ", sendResult);
} else {
console.error("Something went wrong when trying to send this message: ", sendResult);
}
}
}
main();
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<to-phone-number-1>
和<to-phone-number-2>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 <from-phone-number>
的值也可以是短代码(例如 23456)或字母数字发送者 ID(例如 CONTOSO)。
enableDeliveryReport
参数是一个可选参数,可用于配置传送报告。 如果你想要在传送短信后发出事件,则此功能很有用。 请参阅处理短信事件快速入门,了解如何为短信配置传送报告。
tag
参数是可选的。 可以使用该参数将标记应用于传送报告。
使用消息连接全局发送短信
Important
Azure 通信服务的这一功能目前以预览版提供。 预览版中的功能已公开发布,可供所有新客户和现有Microsoft客户使用。
预览版 API 和 SDK 在没有服务级别协议的情况下提供。 建议不要将它们用于生产工作负荷。 某些功能可能不受支持,或者功能可能受到限制。
有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款。
如果使用通过消息连接预配的电话号码,则可以使用标准 Azure 通信服务 JavaScript SDK 发送短信。 唯一的区别是必须包含 messagingConnect
对象来指定合作伙伴名称和 API 密钥。
async function main() {
const sendResults = await smsClient.send({
from: "<from-messaging-connect-number>",
to: ["<to-phone-number-1>", "<to-phone-number-2>"],
message: "Weekly Promotion!"
}, {
// Optional parameters
enableDeliveryReport: true,
tag: "marketing", // custom tag
messagingConnect: {
apiKey: "<partner-api-key>",
partner: "infobip"
}
});
for (const sendResult of sendResults) {
if (sendResult.successful) {
console.log("Success:", sendResult);
} else {
console.error("Failed to send message:", sendResult);
}
}
}
main();
替换以下值:
<from-messaging-connect-number>
:通过 Messaging Connect 获取并链接到 ACS 资源的电话号码。<to-phone-number-1>
和<to-phone-number-2>
:收件人电话号码。<partner-api-key>
:来自消息连接合作伙伴的 API 密钥(例如 Infobip)。
Tip
想要了解有关全局消息传递的详细信息? 查看 “消息连接”页
Warning
电话号码必须遵循 E.164 国际标准格式(例如 +14255550123)。 <from-messaging-connect-number>
必须是已预配并同步到 ACS 资源的 Messaging Connect 号码或动态 Alpha 发送方 ID(例如 CONTOSO)。
该 enableDeliveryReport
参数允许配置传递报告。 该 tag
参数是可选的,可用于向传递报表应用自定义标记。 若要配置短信传递报告,请参阅 “处理 SMS 事件 ”快速入门。
运行代码
Use the node
command to run the code that you added to the send-sms.js file.
node ./send-sms.js
通过使用通信服务 Python 短信 SDK 发送短信,开始使用 Azure 通信服务。
完成本快速入门会从你的 Azure 帐户中扣取最多几美分的费用。
Note
有关本文的最终代码,请参阅 GitHub Azure 示例 使用 Python 管理电话号码。
Prerequisites
Prerequisite check
- 在终端或命令窗口中,运行
python --version
命令来查看是否安装了 Python。 - To view the phone numbers that are associated with your Communication Services resource, sign in to the Azure portal and locate your Communication Services resource. In the navigation pane on the left, select Phone numbers.
设置应用程序环境
若要设置用于发送消息的环境,请完成以下部分。
创建新的 Python 应用程序
打开终端或命令窗口。 使用以下命令为应用创建新目录并导航到该目录。
mkdir sms-quickstart && cd sms-quickstart
Use a text editor to create a file called send-sms.py in the project root directory and add the structure for the program, including basic exception handling.
import os from azure.communication.sms import SmsClient try: # Quickstart code goes here. except Exception as ex: print('Exception:') print(ex)
In the following sections, add all the source code for this quickstart to the send-sms.py file that you created.
安装包
仍在应用程序目录中操作,使用以下命令安装适用于 Python 的 Azure 通信服务短信 SDK 包。
pip install azure-communication-sms
Object model
以下类和接口用于处理适用于 Python 的 Azure 通信服务短信 SDK 的某些主要功能。
Name | Description |
---|---|
SmsClient | 所有短信功能都需要此类。 使用订阅信息对其进行实例化,并使用它发送短信。 |
SmsSendResult | 此类包含来自短信服务的结果。 |
验证客户端
Instantiate an SmsClient with your connection string. 了解如何管理资源的连接字符串。
# Create the SmsClient object that you use to send SMS messages.
sms_client = SmsClient.from_connection_string(<connection_string>)
For simplicity, this quickstart uses connection strings, but in production environments, we recommend using service principals.
发送 1:1 短信
To send an SMS message to a single recipient, call the send
method from the SmsClient with a single recipient phone number. 还可以提供可选参数,以指定是否应启用传送报告,以及设置自定义标记。 Add this code to the end of the try
block in send-sms.py:
# Call send() with SMS values.
sms_responses = sms_client.send(
from_="<from-phone-number>",
to="<to-phone-number>",
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务关联并启用了短信功能的电话号码。 - 将
<to-phone-number>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 <from-phone-number>
的值也可以是短代码(例如 23456)或字母数字发送者 ID(例如 CONTOSO)。
发送 1:N 短信
To send an SMS message to a list of recipients, call the send
method from the SmsClient with a list of recipient phone numbers. 还可以提供可选参数,以指定是否应启用传送报告,以及设置自定义标记。 Add this code to the end of the try
block in send-sms.py:
# Call send() with SMS values.
sms_responses = sms_client.send(
from_="<from-phone-number>",
to=["<to-phone-number-1>", "<to-phone-number-2>"],
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务关联并启用了短信功能的电话号码。 - 将
<to-phone-number-1>
和<to-phone-number-2>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 该值 <from-phone-number>
也可以是短代码,例如 23456 或字母数字发送方 ID,例如 CONTOSO。
Optional parameters
该 enable_delivery_report
参数是可用于配置传递报告的可选参数。 如果要在传递短信时发出事件,请使用此函数。 请参阅 “处理短信事件” 以配置您的短信的传递报告。
tag
参数是一个可选参数,可用于将标记应用于传送报告。
运行代码
从应用程序目录使用 python
命令运行应用程序。
python send-sms.py
完整的 Python 脚本如下代码所示:
import os
from azure.communication.sms import SmsClient
try:
# Create the SmsClient object that you use to send SMS messages.
sms_client = SmsClient.from_connection_string("<connection string>")
# Call send() with SMS values.
sms_responses = sms_client.send(
from_="<from-phone-number>",
to="<to-phone-number>",
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
except Exception as ex:
print('Exception:')
print(ex)
通过使用通信服务 Java 短信 SDK 发送短信,开始使用 Azure 通信服务。
完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。
Note
请参阅最终的代码 Azure 示例 GitHub 使用 Java 发送短信。
Prerequisites
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- Java 开发工具包 (JDK) 版本 8 或更高版本。
- Apache Maven.
- 活动的通信服务资源和连接字符串。 创建通信服务资源。
- 支持短信的电话号码、短代码或字母数字发送者 ID。 获取电话号码。
Prerequisite check
- 在终端或命令窗口中,运行
mvn -v
检查是否安装了 Maven。 - To view the phone numbers that are associated with your Communication Services resource, sign in to the Azure portal and locate your Communication Services resource. In the navigation pane on the left, select Phone numbers.
设置应用程序环境
若要设置用于发送消息的环境,请完成以下部分。
创建新的 Java 应用程序
打开终端或命令窗口,并导航到要在其中创建 Java 应用程序的目录。 若要从 maven-archetype-quickstart 模板生成 Java 项目,请运行以下命令。
- Command Prompt
mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
- PowerShell
mvn archetype:generate "-DgroupId=com.communication.quickstart" "-DartifactId=communication-quickstart" "-DarchetypeArtifactId=maven-archetype-quickstart" "-DarchetypeVersion=1.4" "-DinteractiveMode=false"
generate
目标将创建一个名称与 artifactId
值相同的目录。 Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model (POM).
安装包
Open the pom.xml file in your text editor. 将以下依赖项元素添加到依赖项组。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-sms</artifactId>
<version>1.0.1</version>
</dependency>
设置应用框架
Open /src/main/java/com/communication/quickstart/App.java in a text editor, add import directives, and remove the System.out.println("Hello world!");
statement:
package com.communication.quickstart;
import com.azure.communication.sms.models.*;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.communication.sms.*;
import com.azure.core.util.Context;
import java.util.Arrays;
public class App
{
public static void main( String[] args )
{
// Quickstart code goes here.
}
}
Object model
以下类和接口用于处理适用于 Java 的 Azure 通信服务短信 SDK 的某些主要功能。
Name | Description |
---|---|
SmsClientBuilder | 此类创建 SmsClient。 为此类提供终结点、凭据和 HTTP 客户端。 |
SmsClient | 所有短信功能都需要此类。 用其发送短信。 |
SmsSendOptions | 此类提供用于添加自定义标记和配置传送报告的选项。 如果 deliveryReportEnabled 设置为 true,则在传送成功时将发出一个事件。 |
SmsSendResult | 此类包含来自短信服务的结果。 |
验证客户端
若要对客户端进行身份验证,请使用连接字符串实例化 SmsClient
。 对于凭据,请使用 Azure 门户中的 Key
。 了解如何管理资源的连接字符串。 还可以使用任何实现 com.azure.core.http.HttpClient
接口的自定义 HTTP 客户端来初始化此客户端。
若要实例化客户端,请将以下代码添加到 main
方法:
// You can get your endpoint and access key from your resource in the Azure portal.
String endpoint = "https://<resource-name>.communication.azure.com/";
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key-credential>");
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.buildClient();
还可以使用 connectionString
函数提供整个连接字符串,而不是提供终结点和访问密钥。
// You can get your connection string from your resource in the Azure portal.
String connectionString = "endpoint=https://<resource-name>.communication.azure.com/;accesskey=<access-key>";
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.buildClient();
发送 1:1 短信
若要将短信发送给单个收件人,请使用单个收件人的电话号码从 SmsClient 调用 send
方法。 还可以提供可选参数,以指定是否应启用传送报告,以及设置自定义标记。
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Weekly Promotion");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
在代码中进行下述替换:
- 将
<from-phone-number>
替换为与通信服务资源关联的已启用短信的电话号码。 - 将
<to-phone-number>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 该值 <from-phone-number>
也可以是短代码,例如 23456 或字母数字发送方 ID,例如 CONTOSO。
发送包含选项的 1: N 短信
若要将短信发送到收件人列表,请使用收件人电话号码列表调用 send
方法。 还可以提供可选参数,以指定是否应启用传送报告,以及设置自定义标记。
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Weekly Promotion",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
在代码中进行下述替换:
- 请将
<from-phone-number>
替换为与您的通信服务资源关联的支持短信功能的电话号码 - 将
<to-phone-number-1>
和<to-phone-number-2>
替换为要向其发送消息的电话号码。
Warning
以 E.164 国际标准格式提供电话号码,例如 +14255550123。 <from-phone-number>
的值也可以是短代码(例如 23456)或字母数字发送者 ID(例如 CONTOSO)。
setDeliveryReportEnabled
方法用于配置传送报告。 如果你想要在传送短信后发出事件,则此功能很有用。 请参阅处理短信事件快速入门,了解如何为短信配置传送报告。
若要将标记应用于传递报表,请使用 setTag
该方法。
运行代码
Navigate to the directory that contains the pom.xml file and compile the project using the
mvn
command.mvn compile
生成包。
mvn package
运行以下
mvn
命令以执行应用。- Command Prompt
mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false
- PowerShell
mvn exec:java "-Dexec.mainClass=com.communication.quickstart.App" "-Dexec.cleanupDaemonThreads=false"
使用 Azure 通信服务短信 连接器和 Azure 逻辑应用 创建可发送短信的自动化工作流。
本文介绍如何自动发送短信以响应触发器事件,这是逻辑应用工作流中的第一步。 触发器事件可以是传入的电子邮件、定期计划、 Azure 事件网格 资源事件或 Azure 逻辑应用支持的任何其他触发器。
尽管本文重点介绍如何使用连接器响应触发器,但也可以使用连接器来响应其他动作,这些动作是工作流中接续触发器的步骤。 如果不熟悉逻辑应用,请参阅“ 什么是 Azure 逻辑应用 ”,然后再开始。
Note
完成本文需要从你的 Azure 帐户中扣取最多几美分的费用。
Prerequisites
具备有效订阅的 Azure 帐户,或免费创建一个 Azure 帐户。
有效的 Azure 通信服务资源,或创建一个通信服务资源。
有效的逻辑应用资源(逻辑应用),或创建一个空白逻辑应用,但具有你要使用的触发器。 目前,Azure 通信服务短信连接器仅提供操作,因此逻辑应用至少需要一个触发器。
本快速入门使用 Office 365 Outlook 连接器提供的“新电子邮件到达时”触发器。
支持短信的电话号码、短代码或字母数字发送者 ID。 获取电话号码。
Important
短信和 PSTN 功能取决于所使用的电话号码和所在的国家/地区,具体取决于 Azure 帐单邮寄地址。 For more information, visit the Subscription eligibility documentation.
“添加短信”操作
To add the Send SMS action as a new step in your workflow by using the Azure Communication Services SMS connector, follow these steps in the Azure portal with your logic app workflow open in the Logic App Designer:
On the designer, under the step where you want to add the new action, select New step. 或者,若要在步骤之间添加新操作,请将指针移到这些步骤之间的箭头上方,选择加号 (+),然后选择“添加操作”。
在“选择操作”搜索框中,输入
Azure Communication Services
。 From the actions list, select Send SMS.现在,创建与通信服务资源的连接。
在同一订阅中:
为连接提供一个名称。
选择 Azure 通信服务资源。
Select Create.
使用来自通信服务资源的连接字符串:
为连接提供一个名称。
从下拉选项中选择 ConnectionString 身份验证。
输入来自通信服务资源的连接字符串。
Select Create.
使用服务主体(请参考“创建服务主体”):
为连接提供一个名称。
从下拉选项中选择“服务主体(Microsoft Entra 应用程序)身份验证”。
输入服务主体的租户 ID、客户端 ID 和客户端密码。
输入通信服务资源的通信服务终结点 URL 值。
Select Create.
In the Send SMS action, provide the following information:
源电话号码和目标电话号码。 为了进行测试,你可以使用自己的电话号码作为目标电话号码。
你要发送的短信内容,例如“Hello from Logic Apps!”。
Here's a Send SMS action with example information:
When you're done, on the designer toolbar, select Save.
接下来,运行工作流来进行测试。
测试工作流
To manually start your workflow, on the designer toolbar, select Run. 或者,可等待触发器触发。 无论哪种情况,工作流都应将短信发送到指定的目标电话号码。 有关详细信息,请查看如何运行工作流。
清理工作流资源
若要清理逻辑应用工作流和相关资源,请参阅如何清理逻辑应用资源。
Troubleshooting
若要对与短信发送相关的问题进行故障排除,可以使用事件网格启用短信发送报告,捕获有关发送的详细信息。
清理资源
如果想要清理并删除通信服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。 了解有关清理资源的详细信息。
Toll-free verification
若要使用新的免费电话号码发送短信,必须完成免费验证过程。 有关如何完成免费电话号码验证的指导,请参阅有关如何提交免费验证的快速入门。 只有已经过完全验证的免费电话号码才有权发送短信流量。 系统会阻止从非验证免费电话号码定向到美国和加拿大的电话号码的任何短信流量。
Next steps
本文介绍如何使用 Azure 通信服务发送短信。