Azure 通信服务 SMS Java SDK

azure-communication-sms-java
分类商业
作者Agentic Awesome Skills 社区
许可MIT
评分4.50/5
使用11.7K

Azure Communication SMS (Java)

向单个或多个接收者发送短信,并支持交付报告。

安装

xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-sms</artifactId>
    <version>1.2.0</version>
</dependency>

创建客户端

java
import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.identity.DefaultAzureCredentialBuilder;

// 使用 DefaultAzureCredential (推荐)
SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();

// 使用连接字符串
SmsClient smsClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildClient();

// 使用 AzureKeyCredential
import com.azure.core.credential.AzureKeyCredential;

SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(new AzureKeyCredential("<access-key>"))
.buildClient();

// 异步客户端
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildAsyncClient();

向单个接收者发送短信

java
import com.azure.communication.sms.models.SmsSendResult;

// 简单发送
SmsSendResult result = smsClient.send(
"+14255550100", // 发件人 (您的 ACS 电话号码)
"+14255551234", // 收件人
"您的验证码是 123456");

System.out.println("消息 ID: " + result.getMessageId());
System.out.println("收件人: " + result.getTo());
System.out.println("是否成功: " + result.isSuccessful());

if (!result.isSuccessful()) {
System.out.println("错误: " + result.getErrorMessage());
System.out.println("状态码: " + result.getHttpStatusCode());
}

向多个接收者发送短信

java
import com.azure.communication.sms.models.SmsSendOptions;
import java.util.Arrays;
import java.util.List;

List<String> recipients = Arrays.asList(
"+14255551111",
"+14255552222",
"+14255553333"
);

// 使用配置选项
SmsSendOptions options = new SmsSendOptions()
.setDeliveryReportEnabled(true)
.setTag("marketing-campaign-001");

Iterable<SmsSendResult> results = smsClient.sendWithResponse(
"+14255550100", // 发件人
recipients, // 收件人列表
"限时抢购!仅限今日 5 折。",
options,
Context.NONE
).getValue();

for (SmsSendResult result : results) {
if (result.isSuccessful()) {
System.out.println("已发送至 " + result.getTo() + ": " + result.getMessageId());
} else {
System.out.println("发送至 " + result.getTo() + " 失败: " + result.getErrorMessage());
}
}

发送选项

java
SmsSendOptions options = new SmsSendOptions();

// 启用交付报告 (通过 Event Grid 发送)
options.setDeliveryReportEnabled(true);

// 添加自定义标签用于追踪
options.setTag("order-confirmation-12345");

响应处理

java
import com.azure.core.http.rest.Response;

Response<Iterable<SmsSendResult>> response = smsClient.sendWithResponse(
"+14255550100",
Arrays.asList("+14255551234"),
"Hello!",
new SmsSendOption


s().setDeliveryReportEnabled(true),
Context.NONE
);

// 检查 HTTP 响应
System.out.println("Status code: " + response.getStatusCode());
System.out.println("Headers: " + response.getHeaders());

// 处理结果
for (SmsSendResult result : response.getValue()) {
System.out.println("Message ID: " + result.getMessageId());
System.out.println("Successful: " + result.isSuccessful());

if (!result.isSuccessful()) {
System.out.println("HTTP Status: " + result.getHttpStatusCode());
System.out.println("Error: " + result.getErrorMessage());
}
}

code
## 异步操作
java
import reactor.core.publisher.Mono;

SmsAsyncClient asyncClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildAsyncClient();

// 发送单条消息
asyncClient.send("+14255550100", "+14255551234", "Async message!")
.subscribe(
result -> System.out.println("Sent: " + result.getMessageId()),
error -> System.out.println("Error: " + error.getMessage())
);

// 使用选项发送至多个接收者
SmsSendOptions options = new SmsSendOptions()
.setDeliveryReportEnabled(true);

asyncClient.sendWithResponse(
"+14255550100",
Arrays.asList("+14255551111", "+14255552222"),
"Bulk async message",
options)
.subscribe(response -> {
for (SmsSendResult result : response.getValue()) {
System.out.println("Result: " + result.getTo() + " - " + result.isSuccessful());
}
});

code
## 错误处理
java
import com.azure.core.exception.HttpResponseException;

try {
SmsSendResult result = smsClient.send(
"+14255550100",
"+14255551234",
"Test message"
);

// 单条消息错误不会抛出异常
if (!result.isSuccessful()) {
handleMessageError(result);
}

} catch (HttpResponseException e) {
// 请求级失败(认证、网络等)
System.out.println("Request failed: " + e.getMessage());
System.out.println("Status: " + e.getResponse().getStatusCode());
} catch (RuntimeException e) {
System.out.println("Unexpected error: " + e.getMessage());
}

private void handleMessageError(SmsSendResult result) {
int status = result.getHttpStatusCode();
String error = result.getErrorMessage();

if (status == 400) {
System.out.println("Invalid phone number: " + result.getTo());
} else if (status == 429) {
System.out.println("Rate limited - retry later");
} else {
System.out.println("Error " + status + ": " + error);
}
}

code
## 送达报告

送达报告通过 Azure Event Grid 发送。请为您的 ACS 资源配置 Event Grid 订阅。

java
// Event Grid Webhook 处理程序(在您的端点中)
public void handleDeliveryReport(String eventJson) {
// 解析 Event Grid 事件
// 事件类型: Microsoft.Communication.SMSDeliveryReportReceived

// 事件数据包含:
// - messageId: 对应 SmsSendResult.getMessageId()
// - from: 发送者号码
// - to: 接收者号码
// - deliveryStatus: "Delivered", "Failed" 等
// - deliveryStatusDetails: 详细状态
// - receivedTimestamp: 接收状态的时间戳
// - tag: 来自 SmsSendOptions 的自定义标签
}
code
## SmsSendResult 属性

| 属性 | 类型 | 描述 |
|----------|------|-------------|
| getMessageId() | String | 唯一消息标识符 |
| getTo() | String | 接收者电话号码 |
|
|
isSuccessful() | boolean | 发送是否成功 |
|
getHttpStatusCode() | int | 该接收者的 HTTP 状态码 |
|
getErrorMessage() | String | 失败时的错误详情 |
|
getRepeatabilityResult() | RepeatabilityResult | 幂等性结果 |

环境变量

bash AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=... SMS_FROM_NUMBER=+14255550100 `

最佳实践

1. 电话号码格式 - 使用 E.164 格式:+[国家代码][号码]
2. 交付报告 - 为关键消息(如 OTP、警报)启用交付报告
3. 打标签 - 使用标签将消息与业务上下文关联
4. 错误处理 - 针对每个接收者单独检查
isSuccessful()`
5. 速率限制 - 针对 429 响应实现指数退避重试机制
6. 批量发送 - 针对多个接收者使用批量发送(效率更高)

触发词

  • "send SMS Java", "text message Java"
  • "SMS notification", "OTP SMS", "bulk SMS"
  • "delivery report SMS", "Azure Communication Services SMS"

使用场景

本技能适用于执行概览中所描述的工作流或操作。

局限性

  • 仅在任务明确符合上述范围时使用此技能。
  • 不要将输出视为特定环境验证、测试或专家评审的替代方案。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。