azure-communication-sms-java
microsoft/skills
使用 Azure Communication Services SMS Java SDK,向单个或多个收件人发送短信,并获取送达报告。
...展开全部Azure Communication SMS(Java)
向单个或多个收件人发送短信,并提供送达报告。
安装
com.azure
azure-communication-sms
1.2.0
客户端创建
import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// 本地开发环境:DefaultAzureCredential。生产环境:将 AZURE_TOKEN_CREDENTIALS 设置为 prod 或 AZURE_TOKEN_CREDENTIALS 设置为
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// 或者在生产环境中直接使用特定凭据:
// 参见 https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
// 使用 DefaultAzureCredential(推荐)
SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://.communication.azure.com")
.credential(credential)
.buildClient();
// 使用连接字符串
SmsClient smsClient = new SmsClientBuilder()
.connectionString("")
.buildClient();
// 使用 AzureKeyCredential
import com.azure.core.credential.AzureKeyCredential;
SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://.communication.azure.com")
.credential(new AzureKeyCredential(""))
.buildClient();
// 异步客户端
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
.connectionString("")
.buildAsyncClient();
向单个收件人发送短信
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());
}
向多个收件人发送短信
import com.azure.communication.sms.models.SmsSendOptions;
import java.util.Arrays;
import java.util.List;
List recipients = Arrays.asList(
"+14255551111",
"+14255552222",
"+14255553333"
);
// 设置选项
SmsSendOptions options = new SmsSendOptions()
.setDeliveryReportEnabled(true)
.setTag("marketing-campaign-001");
Iterable results = smsClient.sendWithResponse(
"+14255550100", // 发件人
recipients, // 收件人列表
"限时闪购!仅限今天,五折优惠。",
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());
}
}
发送选项
SmsSendOptions options = new SmsSendOptions();
// 启用投递报告(通过 Event Grid 发送)
options.setDeliveryReportEnabled(true);
// 添加自定义标签用于跟踪
options.setTag("order-confirmation-12345");
响应处理
import com.azure.core.http.rest.Response;
Response<Iterable> response = smsClient.sendWithResponse(
"+14255550100",
Arrays.asList("+14255551234"),
"Hello!",
new SmsSendOptions().setDeliveryReportEnabled(true),
Context.NONE
);
// 检查 HTTP 响应
System.out.println("状态码: " + response.getStatusCode());
System.out.println("请求头: " + response.getHeaders());
// 处理结果
for (SmsSendResult result : response.getValue()) {
System.out.println("消息 ID:" + result.getMessageId());
System.out.println("是否成功:" + result.isSuccessful());
if (!result.isSuccessful()) {
System.out.println("HTTP 状态码: " + result.getHttpStatusCode());
System.out.println("错误: " + result.getErrorMessage());
}
}
异步操作
import reactor.core.publisher.Mono;
SmsAsyncClient asyncClient = new SmsClientBuilder()
.connectionString("")
.buildAsyncClient();
// 发送单条消息
asyncClient.send("+14255550100", "+14255551234", "异步消息!")
.subscribe(
result -> System.out.println("已发送: " + result.getMessageId()),
error -> System.out.println("错误: " + error.getMessage())
);
// 带选项向多个号码发送
SmsSendOptions options = new SmsSendOptions()
.setDeliveryReportEnabled(true);
asyncClient.sendWithResponse(
"+14255550100",
Arrays.asList("+14255551111", "+14255552222"),
"批量异步消息",
options)
.subscribe(response -> {
for (SmsSendResult result : response.getValue()) {
System.out.println("结果: " + result.getTo() + " - " + result.isSuccessful());
}
});
错误处理
import com.azure.core.exception.HttpResponseException;
try {
SmsSendResult result = smsClient.send(
"+14255550100",
"+14255551234",
"测试消息"
);
// 单条消息错误不会抛出异常
if (!result.isSuccessful()) {
handleMessageError(result);
}
} catch (HttpResponseException e) {
// 请求级别的失败(身份验证、网络等)
System.out.println("请求失败:" + e.getMessage());
System.out.println("状态码:" + e.getResponse().getStatusCode());
} catch (RuntimeException e) {
System.out.println("意外错误:" + e.getMessage());
}
private void handleMessageError(SmsSendResult result) {
int status = result.getHttpStatusCode();
String error = result.getErrorMessage();
if (status == 400) {
System.out.println("手机号码无效:" + result.getTo());
} else if (status == 429) {
System.out.println("请求速率受限 - 稍后重试");
} else {
System.out.println("错误 " + status + ": " + error);
}
}
投递报告
投递报告通过 Azure Event Grid 发送。请为您的 ACS 资源配置一个 Event Grid 订阅。
// Event Grid webhook 处理程序(位于您的端点中)
public void handleDeliveryReport(String eventJson) {
// 解析 Event Grid 事件
// 事件类型:Microsoft.Communication.SMSDeliveryReportReceived
// 事件数据包含:
// - messageId:与 SmsSendResult.getMessageId() 对应
// - from:发件人号码
// - to:收件人号码
// - deliveryStatus:“已送达”、“失败”等
// - deliveryStatusDetails:详细状态
// - receivedTimestamp:接收状态的时间戳
// - tag:来自 SmsSendOptions 的自定义标签
}
SmsSendResult 属性
| 属性 | 类型 | 描述 |
|---|---|---|
getMessageId() |
字符串 | 唯一的消息标识符 |
getTo() |
字符串 | 收件人电话号码 |
isSuccessful() |
布尔值 | 发送是否成功 |
getHttpStatusCode() |
int | 此收件人的 HTTP 状态码 |
getErrorMessage() |
字符串 | 失败时的错误详情 |
getRepeatabilityResult() |
RepeatabilityResult | 幂等性结果 |
环境变量
AZURE_COMMUNICATION_ENDPOINT=https://.communication.azure.com # 所有身份验证方法均需此项
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=... # Entra ID 身份验证的替代方案
SMS_FROM_NUMBER=+14255550100 # 发件人电话号码必填
AZURE_TOKEN_CREDENTIALS=prod # 仅当在生产环境中使用 DefaultAzureCredential 时才需要
最佳实践
- 电话号码格式- 请使用 E.164 格式:
+[国家代码][号码] - 投递报告- 针对关键消息(一次性密码、警报)应启用此功能
- 标签- 使用标签将消息与业务场景关联
- 错误处理- 针对每位收件人单独检查
isSuccessful()函数 - 速率限制- 针对 429 响应,实现带退避机制的重试
- 批量发送- 向多个收件人发送时使用批量发送(更高效)
触发短语
- “Java 发送短信”、“Java 短消息”
- “短信通知”、“OTP短信”、“群发短信”
- “短信送达回执”、“Azure Communication Services 短信”
---
name: azure-communication-sms-java
description: Send SMS messages to single or multiple recipients with delivery reporting using the Azure Communication Services SMS Java SDK.
license: MIT
---
# Azure Communication SMS (Java)
Send SMS messages to single or multiple recipients with delivery reporting.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-sms</artifactId>
<version>1.2.0</version>
</dependency>
```
## Client Creation
```java
import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
// With DefaultAzureCredential (recommended)
SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(credential)
.buildClient();
// With connection string
SmsClient smsClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildClient();
// With AzureKeyCredential
import com.azure.core.credential.AzureKeyCredential;
SmsClient smsClient = new SmsClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(new AzureKeyCredential("<access-key>"))
.buildClient();
// Async client
SmsAsyncClient smsAsyncClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildAsyncClient();
```
## Send SMS to Single Recipient
```java
import com.azure.communication.sms.models.SmsSendResult;
// Simple send
SmsSendResult result = smsClient.send(
"+14255550100", // From (your ACS phone number)
"+14255551234", // To
"Your verification code is 123456");
System.out.println("Message ID: " + result.getMessageId());
System.out.println("To: " + result.getTo());
System.out.println("Success: " + result.isSuccessful());
if (!result.isSuccessful()) {
System.out.println("Error: " + result.getErrorMessage());
System.out.println("Status: " + result.getHttpStatusCode());
}
```
## Send SMS to Multiple Recipients
```java
import com.azure.communication.sms.models.SmsSendOptions;
import java.util.Arrays;
import java.util.List;
List<String> recipients = Arrays.asList(
"+14255551111",
"+14255552222",
"+14255553333"
);
// With options
SmsSendOptions options = new SmsSendOptions()
.setDeliveryReportEnabled(true)
.setTag("marketing-campaign-001");
Iterable<SmsSendResult> results = smsClient.sendWithResponse(
"+14255550100", // From
recipients, // To list
"Flash sale! 50% off today only.",
options,
Context.NONE
).getValue();
for (SmsSendResult result : results) {
if (result.isSuccessful()) {
System.out.println("Sent to " + result.getTo() + ": " + result.getMessageId());
} else {
System.out.println("Failed to " + result.getTo() + ": " + result.getErrorMessage());
}
}
```
## Send Options
```java
SmsSendOptions options = new SmsSendOptions();
// Enable delivery reports (sent via Event Grid)
options.setDeliveryReportEnabled(true);
// Add custom tag for tracking
options.setTag("order-confirmation-12345");
```
## Response Handling
```java
import com.azure.core.http.rest.Response;
Response<Iterable<SmsSendResult>> response = smsClient.sendWithResponse(
"+14255550100",
Arrays.asList("+14255551234"),
"Hello!",
new SmsSendOptions().setDeliveryReportEnabled(true),
Context.NONE
);
// Check HTTP response
System.out.println("Status code: " + response.getStatusCode());
System.out.println("Headers: " + response.getHeaders());
// Process results
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());
}
}
```
## Async Operations
```java
import reactor.core.publisher.Mono;
SmsAsyncClient asyncClient = new SmsClientBuilder()
.connectionString("<connection-string>")
.buildAsyncClient();
// Send single message
asyncClient.send("+14255550100", "+14255551234", "Async message!")
.subscribe(
result -> System.out.println("Sent: " + result.getMessageId()),
error -> System.out.println("Error: " + error.getMessage())
);
// Send to multiple with options
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());
}
});
```
## Error Handling
```java
import com.azure.core.exception.HttpResponseException;
try {
SmsSendResult result = smsClient.send(
"+14255550100",
"+14255551234",
"Test message"
);
// Individual message errors don't throw exceptions
if (!result.isSuccessful()) {
handleMessageError(result);
}
} catch (HttpResponseException e) {
// Request-level failures (auth, network, etc.)
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);
}
}
```
## Delivery Reports
Delivery reports are sent via Azure Event Grid. Configure an Event Grid subscription for your ACS resource.
```java
// Event Grid webhook handler (in your endpoint)
public void handleDeliveryReport(String eventJson) {
// Parse Event Grid event
// Event type: Microsoft.Communication.SMSDeliveryReportReceived
// Event data contains:
// - messageId: correlates to SmsSendResult.getMessageId()
// - from: sender number
// - to: recipient number
// - deliveryStatus: "Delivered", "Failed", etc.
// - deliveryStatusDetails: detailed status
// - receivedTimestamp: when status was received
// - tag: your custom tag from SmsSendOptions
}
```
## SmsSendResult Properties
| Property | Type | Description |
|----------|------|-------------|
| `getMessageId()` | String | Unique message identifier |
| `getTo()` | String | Recipient phone number |
| `isSuccessful()` | boolean | Whether send succeeded |
| `getHttpStatusCode()` | int | HTTP status for this recipient |
| `getErrorMessage()` | String | Error details if failed |
| `getRepeatabilityResult()` | RepeatabilityResult | Idempotency result |
## Environment Variables
```bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com # Required for all auth methods
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=... # Alternative to Entra ID auth
SMS_FROM_NUMBER=+14255550100 # Required for the sender phone number
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Best Practices
1. **Phone Number Format** - Use E.164 format: `+[country code][number]`
2. **Delivery Reports** - Enable for critical messages (OTP, alerts)
3. **Tagging** - Use tags to correlate messages with business context
4. **Error Handling** - Check `isSuccessful()` for each recipient individually
5. **Rate Limiting** - Implement retry with backoff for 429 responses
6. **Bulk Sending** - Use batch send for multiple recipients (more efficient)
## Trigger Phrases
- "send SMS Java", "text message Java"
- "SMS notification", "OTP SMS", "bulk SMS"
- "delivery report SMS", "Azure Communication Services SMS"
所有文件
0 个文件安装 azure-communication-sms-java
下载技能文件并将其解压到 .claude/skills/ 目录中。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-communication-sms-java # Copy SKILL.md to your .claude/skills/ directory
复制





首页
