azure-communication-sms-java
microsoft/skills
使用 Azure Communication Services SMS Java SDK,向單一或多位收件者傳送簡訊,並取得傳送回報。
...展開全部Azure Communication SMS (Java)
向單一或多個收件者傳送 SMS 訊息,並提供傳送回報。
安裝
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();
向單一收件者發送 SMS
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() |
整數 | 此收件者的 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 通訊服務簡訊」
---
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
複製





首頁
