azure-communication-sms-java
microsoft/skills
Azure Communication Services SMS Java SDK を使用して、配信状況のレポート機能付きで、1人または複数の受信者にSMSメッセージを送信します。
...すべて拡張しますAzure Communication SMS (Java)
配信状況レポート機能付きで、1人または複数の受信者に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());
}
複数の受信者にSMSを送信する
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, // 宛先リスト
"フラッシュセール!本日限定50%オフ。",
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", "Async message!")
.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"),
"Bulk async message",
options)
.subscribe(response -> {
for (SmsSendResult result : response.getValue()) {
System.out.println("Result: " + 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: "Delivered"、"Failed" など
// - deliveryStatusDetails: 詳細なステータス
// - receivedTimestamp: ステータスが受信された時刻
// - tag: SmsSendOptionsで指定したカスタムタグ
}
SmsSendResultのプロパティ
| プロパティ | 型 | 説明 |
|---|---|---|
getMessageId() |
文字列 | 一意のメッセージ識別子 |
getTo() |
文字列 | 受信者の電話番号 |
isSuccessful() |
boolean | 送信が成功したかどうか |
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形式を使用してください:
+[国コード][番号] - 配信レポート- 重要なメッセージ(OTP、アラート)については有効にしてください
- タグ付け- タグを使用して、メッセージとビジネスコンテキストを関連付ける
- エラー処理- 受信者ごとに個別に
isSuccessful()を確認してください - レート制限- 429レスポンスに対しては、バックオフを伴う再試行を実装する
- 一括送信- 複数の受信者にはバッチ送信を使用する(より効率的)
トリガーフレーズ
- 「JavaでSMSを送信」、「Javaでテキストメッセージを送信」
- 「SMS通知」、「OTP SMS」、「一括SMS」
- 「配信報告SMS」、「Azure Communication Services SMS」
---
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
コピー





家
